Hello
New to Java here coming from .NET
Trying to implement PKCS7 signing using Java similar to a previous .NET implementation.
Problem is am not able to get the same output.
Same keystore converted from P12 to JKS.
.NET Code
Java Code
Please advise on what I might be doing wrong. I picked up this method online and am open to alternatives if someone has an easier method to implement this.
Thanks
New to Java here coming from .NET
Trying to implement PKCS7 signing using Java similar to a previous .NET implementation.
Problem is am not able to get the same output.
Same keystore converted from P12 to JKS.
.NET Code
Code:
Dim str As String = "test"
' Signing
Dim signerCert As New X509Certificate2(keyPath, keyPass)
Dim data As Byte() = System.Text.Encoding.Default.GetBytes(str)
Dim content As New Pkcs.ContentInfo(data)
Dim signed As New Pkcs.SignedCms(content)
Dim signer As New Pkcs.CmsSigner(signerCert)
signer.IncludeOption = X509IncludeOption.EndCertOnly
signed.ComputeSignature(signer)
Dim signedBytes As Byte() = signed.Encode()
Dim signedBytesBase64 As String = Convert.ToBase64String(signedBytes)
' End Signing
TextBox1.Text = signedBytesBase64
Code:
String body = "test";
//digitally sign the message body
//First load the keystore object by providing the JKS file path
KeyStore clientStore = KeyStore.getInstance("JKS");
//replace testPass with the p12 password/pin
clientStore.load(new FileInputStream(keyPath), keyPass.toCharArray());
X509Certificate c = (X509Certificate)clientStore.getCertificate("certalias");
//Data to sign
byte[] dataToSign = body.getBytes();
//compute signature:
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign((PrivateKey)clientStore.getKey("certalias", keyPass.toCharArray()));
signature.update(dataToSign);
byte[] signedData = signature.sign();
//load X500Name
X500Name xName = X500Name.asX500Name(c.getSubjectX500Principal());
//load serial number
BigInteger serial = c.getSerialNumber();
//laod digest algorithm
AlgorithmId digestAlgorithmId = new AlgorithmId(AlgorithmId.SHA_oid);
//load signing algorithm
AlgorithmId signAlgorithmId = new AlgorithmId(AlgorithmId.RSAEncryption_oid);
//Create SignerInfo:
SignerInfo sInfo = new SignerInfo(xName, serial, digestAlgorithmId, signAlgorithmId, signedData);
//Create ContentInfo:
ContentInfo cInfo = new ContentInfo(ContentInfo.DATA_OID, new DerValue(DerValue.tag_OctetString, dataToSign));
//Create PKCS7 Signed data
PKCS7 p7 = new PKCS7(new AlgorithmId[] { digestAlgorithmId }, cInfo,
new java.security.cert.X509Certificate[] { c },
new SignerInfo[] { sInfo });
//Write PKCS7 to bYteArray
ByteArrayOutputStream bOut = new DerOutputStream();
p7.encodeSignedData(bOut);
byte[] encodedPKCS7 = bOut.toByteArray();
String signedBody = Base64.getEncoder().encodeToString(encodedPKCS7);
Thanks