使用MSCAPI& amp;标记来自usb令牌的PDF iText的

时间:2013-05-15 07:25:41

标签: java encryption itext digital-signature mscapi

任何人都可以使用MSCAPI和ITEXT从usb令牌给我一个简单的pdf签名示例。我不想使用固定的ocsp字符串。

我试着遵循这个 Digital Signature book 但它没有用。我的代码是:

        LoggerFactory.getInstance().setLogger(new SysoLogger());
        BouncyCastleProvider providerBC = new BouncyCastleProvider();
        Security.addProvider(providerBC);
        SunMSCAPI provdierMSCAP = new SunMSCAPI();
        Security.addProvider(provdierMSCAP);
        KeyStore ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);

        String alias = (String)ks.aliases().nextElement();
        PrivateKey pk = (PrivateKey)ks.getKey(alias, null);
        Certificate[] chain = ks.getCertificateChain(alias);


        PdfReader pdfreader = new PdfReader("HelloWorld.pdf");
        FileOutputStream outputFile = new FileOutputStream("Signed.pdf");
        PdfStamper pdfstamper;

        pdfstamper =  PdfStamper.createSignature(pdfreader, outputFile, '\0', null, true);

        PdfSignatureAppearance sap = pdfstamper.getSignatureAppearance();
        sap.setCrypto(pk, chain, null, PdfSignatureAppearance.SELF_SIGNED);
        sap.setReason("Test");
        sap.setLocation("Dhaka");

        sap.setVisibleSignature(new Rectangle(10, 10, 50, 30), 1, "Test");
        pdfstamper.close();

        JOptionPane.showMessageDialog(null, "Successfully Signed");

它给了我以下错误:

        java.lang.NullPointerException

我尝试使用itext 5.2.1 / itextpdf-5.3.5和bcmail-jdk16-1.46,bcprov-jdk16-1.46.jar,bctsp-jdk16-1.46.jar。

有人可以帮忙吗?请................

3 个答案:

答案 0 :(得分:0)

您将空值传递给load(),试试这个

ks.load(new FileInputStream("certificate_path"), keystore_password.toCharArray());

答案 1 :(得分:0)

删除sap.setCrypto行。你不需要它。

答案 2 :(得分:0)

在最新版本中,setCrypo替换为以下几行:

ExternalDigest digest = new BouncyCastleDigest();
BouncyCastleProvider provider = new BouncyCastleProvider();
ExternalSignature signature = new PrivateKeySignature(key, DigestAlgorithms.SHA256, provider.getName());
MakeSignature.signDetached(sap, digest, signature, chain,   null, null, null, 0, CryptoStandard.CMS);

您必须将 bcprov-jdk15on-1.60.jar bcpkix-jdk15on-1.60.jar 放入您的类路径中。