我想用itext和智能卡签署一份pdf。如果我将智能卡放入阅读器,Windows会自动在商店中添加两个证书。我阅读了Bruno Lowagie的书,我试图制作一个样本添加图像和其他一些东西:
public static void main(String[] args)
throws GeneralSecurityException, IOException, DocumentException {
BouncyCastleProvider provider = new BouncyCastleProvider();
Security.addProvider(provider);
KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
//KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, PASSWORD);
String alias = (String) ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
Certificate[] chain = ks.getCertificateChain(alias);
sign(SRC, String.format(DEST, 1), chain, pk, DigestAlgorithms.SHA256,
provider.getName(), CryptoStandard.CMS, "Test 1", "Ghent", "signHere");
sign(SRC, String.format(DEST, 2), chain, pk, DigestAlgorithms.SHA512,
provider.getName(), CryptoStandard.CMS, "Test 2", "Ghent", "signHere");
sign(SRC, String.format(DEST, 3), chain, pk, DigestAlgorithms.SHA256,
provider.getName(), CryptoStandard.CADES, "Test 3", "Ghent", "signHere");
sign(SRC, String.format(DEST, 4), chain, pk, DigestAlgorithms.RIPEMD160,
provider.getName(), CryptoStandard.CADES, "Test 4", "Ghent", "signHere");
}
public static void sign(String src, String dest, Certificate[] chain, PrivateKey pk,
String digestAlgorithm, String provider, CryptoStandard subfilter,
String reason, String location, String fieldToSign)
throws GeneralSecurityException, IOException, DocumentException {
// Creating the reader and the stamper
PdfReader reader = new PdfReader(src);
FileOutputStream os = new FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
// Creating the appearance
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
appearance.setReason(reason);
appearance.setLocation(location);
appearance.setVisibleSignature(fieldToSign);
appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS);
appearance.setImage(Image.getInstance(Params.imgPath));
appearance.setImageScale(-1);
// Creating the signature
ExternalDigest digest = new BouncyCastleDigest();
ExternalSignature signature = new PrivateKeySignature(pk, digestAlgorithm, provider);
MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, subfilter);
}
但我得到的是java.security.InvalidKeyException:提供的密钥(sun.security.mscapi.RSAPrivateKey)不是RSAPrivateKey实例
为什么sun.security.mscapi.RSAPrivateKey不是RSAPrivateKey实例?我在这里做错了什么?我和BouncyCastle jars 1.49和1.50
都有这个错误答案 0 :(得分:2)
问题是您在创建签名时传递的提供程序:
ExternalSignature signature = new PrivateKeySignature(pk, digestAlgorithm, provider);
提供者必须是ks.getProvider()。getName()(或" SunMSCAPI")而不是BouncyCastleProvider。
答案 1 :(得分:0)
在PrivateKeySignature的构造函数中将提供程序名称更改为" SunMSCAPI"。