有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    虽然这个问题已经很老了,但我想创建一个参考答案来链接。我不久前修改了e-Id applet代码,现在可以签名了

    查看POIs documentation了解更多详细信息

    基本代码如下:

    // loading the keystore - pkcs12 is used here, but of course jks & co are also valid
    // the keystore needs to contain a private key and it's certificate having a
    // 'digitalSignature' key usage
    char password[] = "test".toCharArray();
    File file = new File("test.pfx");
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    FileInputStream fis = new FileInputStream(file);
    keystore.load(fis, password);
    fis.close();
    
    // extracting private key and certificate
    String alias = "xyz"; // alias of the keystore entry
    Key key = keystore.getKey(alias, password);
    X509Certificate x509 = (X509Certificate)keystore.getCertificate(alias);
    
    // filling the SignatureConfig entries (minimum fields, more options are available ...)
    SignatureConfig signatureConfig = new SignatureConfig();
    signatureConfig.setKey(keyPair.getPrivate());
    signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
    OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ_WRITE);
    signatureConfig.setOpcPackage(pkg);
    
    // adding the signature document to the package
    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(signatureConfig);
    si.confirmSignature();
    // optionally verify the generated signature
    boolean b = si.verifySignature();
    assert (b);
    // write the changes back to disc
    pkg.close();