Reputation: 29
I need to sign a PDF using the PDFBox library and AWS CloudHSM.
In itext its working fine but while using some other way it is showing invalid signature.Below are the codes
Working code -:
public byte[] signUsingDigest(String digestBASE64,PrivateKey pk, Certificate[] chain) throws Exception {
PrivateKeySignature signature = new PrivateKeySignature(pk, "SHA256", manager.getProvider().getName());
String hashAlgorithm = signature.getHashAlgorithm();
BouncyCastleDigest digest = new BouncyCastleDigest();
PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, digest, false);
byte[] hash = Base64.decodeBase64(digestBASE64);
byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CMS, null, null);
byte[] extSignature = signature.sign(sh);
sgn.setExternalDigest(extSignature, null, signature.getEncryptionAlgorithm());
// return sgn.getEncodedPKCS7(hash, null, null, null,PdfSigner.CryptoStandard.CMS);
byte[] pkcs7digitalSigned = sgn.getEncodedPKCS7(hash, PdfSigner.CryptoStandard.CMS, null, null, null);
return pkcs7digitalSigned;
}
But when i want to remove itext code with below code its showing invalid signature
public byte[] signUsingDigest(String digestBASE64, PrivateKey pk, Certificate[] chain ) throws Exception {
byte[] hash = Base64.decodeBase64(digestBASE64);
// Create the signed attributes using BouncyCastle
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
List<Certificate> certList = Arrays.asList(chain);
JcaCertStore certs = new JcaCertStore(certList);
ContentSigner sha256Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider(manager.getProvider().getName()).build(pk);
generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().build()).build(sha256Signer, (X509Certificate) chain[0]));
generator.addCertificates(certs);
CMSProcessableByteArray contentBytesCMS = new CMSProcessableByteArray(hash);
CMSSignedData signedData = generator.generate(contentBytesCMS, false);
return signedData.getEncoded();
}
Upvotes: 0
Views: 93