我使用在此页面上找到的以下代码使用 *.p12 文件对 PDF 进行签名。
public static final boolean signPdf()
throws IOException, DocumentException, Exception
{
// Vous devez preciser ici le chemin d'acces a votre clef pkcs12
String fileKey = "C:\\MonRep\\MaClef.p12" ;
// et ici sa "passPhrase"
String fileKeyPassword = "MonPassword" ;
try {
// Creation d'un KeyStore
KeyStore ks = KeyStore.getInstance("pkcs12");
// Chargement du certificat p12 dans el magasin
ks.load(new FileInputStream(fileKey), fileKeyPassword.toCharArray());
String alias = (String)ks.aliases().nextElement();
// Recupération de la clef privée
PrivateKey key = (PrivateKey)ks.getKey(alias, fileKeyPassword.toCharArray());
// et de la chaine de certificats
Certificate[] chain = ks.getCertificateChain(alias);
// Lecture du document source
PdfReader pdfReader = new PdfReader((new File(fname)).getAbsolutePath());
File outputFile = new File(fnameS);
// Creation du tampon de signature
PdfStamper pdfStamper;
pdfStamper = PdfStamper.createSignature(pdfReader, null, '\0', outputFile);
PdfSignatureAppearance sap = pdfStamper.getSignatureAppearance();
sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
sap.setReason("Test SignPDF berthou.mc");
sap.setLocation("");
// Position du tampon sur la page (ici en bas a gauche page 1)
sap.setVisibleSignature(new Rectangle(10, 10, 50, 30), 1, "sign_rbl");
pdfStamper.setFormFlattening(true);
pdfStamper.close();
return true;
}
catch (Exception key) {
throw new Exception(key);
}
}
该代码在我的计算机上运行良好。但是如果我用 eclipse 创建一个 .war 文件并将其部署在服务器上,服务器会抛出 javax.crypto.BadPaddingException:
java.io.IOException: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1317)
at java.security.KeyStore.load(KeyStore.java:1214)
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.PKCS12PBECipherCore.implDoFinal(PKCS12PBECipherCore.java:355)
at com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndRC2_40.engineDoFinal(PKCS12PBECipherCore.java:462)
at javax.crypto.Cipher.doFinal(Cipher.java:1922)
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1308)
... 27 more
我在其他线程中找到的所有信息都表明我用来加载 KeyStore 的密码是错误的,但我确信它没有错。
有什么想法吗?非常感谢!