gpt4 book ai didi

java - iText 和数字签名

转载 作者:行者123 更新时间:2023-11-30 06:20:19 25 4
gpt4 key购买 nike

我尝试使用 iText for JAVA 和葡萄牙公民卡(智能卡)在 pdf 中创建签名。但是当代码执行 MakeSignature 类时,我总是收到一条错误消息:

java.security.InvalidKeyException: Supplied key (sun.security.pkcs11.P11Key$P11PrivateKey) is not a RSAPrivateKey instance

我需要一些帮助,有人可以帮助我吗?

 try {
String pkcs11Config = "name=GemPC" + "\n" + "library=C:/WINDOWS/system32/pteidpkcs11.dll";
ByteArrayInputStream configStream = new ByteArrayInputStream(pkcs11Config.getBytes());
Provider pkcs11Provider = new sun.security.pkcs11.SunPKCS11(configStream);

Security.addProvider(pkcs11Provider);
CallbackHandler cmdLineHdlr = new DialogCallbackHandler();

KeyStore.Builder builder = KeyStore.Builder.newInstance("PKCS11", pkcs11Provider,
new KeyStore.CallbackHandlerProtection(cmdLineHdlr));

KeyStore ks = builder.getKeyStore();

PdfReader pdf = new PdfReader(filePath);
FileOutputStream fos = new FileOutputStream(dest);
PdfStamper stp = PdfStamper.createSignature(pdf, fos, '\0');
PdfSignatureAppearance sap = stp.getSignatureAppearance();
sap.setReason("I'm the author");

String alias = (String) ks.aliases().nextElement();

PrivateKey pk = (PrivateKey) ks.getKey("CITIZEN SIGNATURE CERTIFICATE", null);
Certificate chain = ks.getCertificate(alias);

X509Certificate x509 = (X509Certificate) chain;
x509.checkValidity();

ExternalSignature es = new PrivateKeySignature(pk, "SHA-1", "BC");
ExternalDigest digest = new BouncyCastleDigest();
Certificate[] certs = new Certificate[1];
certs[0] = chain;

MakeSignature.signDetached(sap, digest, es, certs, null, null, null, 0, CryptoStandard.CMS);
return dest;
} catch (CertificateExpiredException | CertificateNotYetValidException ex) {
Logger.getLogger(Signer.class.getName()).log(Level.SEVERE, null, ex);
return null;
}

最佳答案

如果您的私钥在智能卡 (PKCS11) 中,则无法将此 key 包装在 java.security.interfaces.RSAPrivateKey 中,因为您的 key Material 位于安全设备中。

所以您可能必须更改代码中的提供程序:

 ExternalSignature es = new PrivateKeySignature(pk, "SHA-1", "BC");

对于:

 ExternalSignature es = new PrivateKeySignature(pk, "SHA-1", pkcs11Provider.getName());

希望对您有所帮助,

关于java - iText 和数字签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21986956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com