I need to sign a PDF using the PDFBox library and AWS CloudHSM. I tried to do it by following the next steps:
- Insert data into a PDF
- Calculate a PDF digest
- Send the PDF digest to the AWS CloudHSM and sign it
- Insert this signature into the PDF As a result, my PDF document hasn't been signed. The calculating PDF digest code:
public byte[] getDigest(byte[] pdf) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (PDDocument pdfDocument = PDDocument.load(pdf)) {
// add signature dictionary
ExternalSigningSupport externalSigningSupport = pdfDocument.saveIncrementalForExternalSigning(out);
byte[] dataToSign;
try (final InputStream content = externalSigningSupport.getContent()) {
dataToSign = IOUtils.toByteArray(content);
final MessageDigest digest = MessageDigest.getInstance("SHA256");
return digest.digest(dataToSign);
}
}
}
Then I sent this digest to the AWS CloudHSM
public byte[] signViaHSM(byte[] pdfDigest) {
if (Security.getProvider(CloudHsmProvider.PROVIDER_NAME) == null) {
Security.addProvider(new CloudHsmProvider());
}
keyStore = KeyStoreWithAttributes.getInstance(CloudHsmProvider.PROVIDER_NAME);
keyStore.load(null, null);
KeyAttributesMap keyAttributes = new KeyAttributesMap();
keyAttributes.put(KeyAttribute.LABEL, aliasName);
keyAttributes.put(KeyAttribute.OBJECT_CLASS, ObjectClassType.PRIVATE_KEY);
PrivateKey pk = (PrivateKey) keyStore.getKey(attributes);
Signature sig = Signature.getInstance(signingAlgorithm.toString(), CloudHsmProvider.PROVIDER_NAME);
sig.initSign(privateKey);
sig.update(documentBytes);
return sig.sign();
}
Insert signature to the PDF
public void insertSignature(byte[] signature, ExternalSigningSupport signing) {
...
signing.setSignature(signature)
}
Then I downloaded the PDF document, and this one is broken.
Can anyone help me insert the signature into the pkcs7 container and sign the PDF?
Where is my issue?
What am I doing wrong?