I generate and digitally sign correctly a pdf using iText.
When I try to sign it again (two or three times) the pdf says that the previuos revision is been modified and the first signature is not valid, but I've just signed it on another time without touching nothing else.
This is my code:
public void signPdf(String SRC, String DEST, String SIGN_IMAGE)
throws IOException, DocumentException, GeneralSecurityException {
// Gets the informations stored in the properties file
String path = properties.getProperty("PRIVATE");
String keystore_password = properties.getProperty("PASSWORD");
String key_password = properties.getProperty("PASSWORD");
// Create the keystore
KeyStore ks = KeyStore.getInstance("pkcs12", "BC");
ks.load(new FileInputStream(path), keystore_password.toCharArray());
String alias = (String) ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias,
key_password.toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);
// reader and stamper
PdfReader reader = new PdfReader(SRC);
FileOutputStream os = new FileOutputStream(DEST);
// Get all the signatures if existing
AcroFields acroFields = reader.getAcroFields();
List<String> signatureNames = acroFields.getSignatureNames();
PdfStamper stamper;
// Choose to append or not the signature
if(signatureNames.isEmpty()){
stamper = PdfStamper.createSignature(reader, os, '\0');
} else{
stamper = PdfStamper.createSignature(reader, os, '\0', null,
true);
}
String sName = "sign_" + (signatureNames.size());
// appearance
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
appearance.setVisibleSignature(new Rectangle(x_bl, y_bl, x_tr, y_tr),
page, sName);
appearance
.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
appearance.setSignatureGraphic(Image.getInstance(SIGN_IMAGE));
// digital signature
ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, digest, es, chain, null, null,
null, 0, CryptoStandard.CMS);
}
I'm not getting what's really wrong because when I used to sign it just twice separately like in this example it used to work. What am I doing wrong?