iText和数字签名

时间:2014-02-24 11:51:33

标签: java pdf pdf-generation itext digital-signature

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

  

java.security.InvalidKeyException:提供的密钥(sun.security.pkcs11.P11Key $ P11PrivateKey)不是RSAPrivateKey实例

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

 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;
    }

1 个答案:

答案 0 :(得分:5)

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

因此,您可能必须更改代码中的提供程序:

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

有:

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

希望这有帮助,