【问题标题】:Get Certificate and Signature values in Java在 Java 中获取证书和签名值
【发布时间】:2014-02-04 16:47:40
【问题描述】:

我有一个需要调用 Web 服务的要求。为了调用该 Web 服务,我需要在 Java 的 SOAP 请求中提供证书链和签名值(Web 服务中的数据类型是字符串)。

我已经使用 wsimport 从 wsdl 生成了源代码,并在我的 Java 程序中使用了它。我有一个数字签名证书文件 (certificateFile.pfx)(我可以使用密码)。

最终的 SOAP 消息示例应该是这样的

<soapenv:Envelope
    xmlns:soapenv = "http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:v = "http://www.something.com">
    <soapenv:Header/>
    <soapenv:Body>
        <v:Auth>
            <v:userID>xxxxxxxxxx</v:userID>
            <v:password>xxxxxxxxxx</v:password>
            <v:certChain>xxxxxxxxxx</v:certChain>
            <v:signature>xxxxxxxxxx</v:signature>
        </v:Auth>
    </soapenv:Body>
</soapenv:Envelope>

从 WSDL 生成 java 源代码后,对于 Auth,我设置了这样的值。 (以下 4 个字段均为字符串数据类型)

Auth authInfo = new Auth();
authInfo.setUserID(userId);
authInfo.setPassword(password);
authInfo.setCertChain("");
authInfo.setSignature("");

这里我没有为 CertChain 和 Signature 设置什么。

由于我有证书文件,所以我尝试了这个

XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
// Load the KeyStore and get the signing key and certificate.
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(new File(certificateName)),
                            certificatePassword.toCharArray());
KeyStore.PrivateKeyEntry keyEntry =
    (KeyStore.PrivateKeyEntry) ks.getEntry(
        certificateAlias,
        new KeyStore.PasswordProtection(
            certificatePassword.toCharArray()));
X509Certificate cert =
    (X509Certificate) keyEntry.getCertificate();

使用过

authInfo.setSignature(new String(cert.getSignature()));

但没有一个有效。 cert.getSignature() 返回二进制数据而不是真正的字符串。

我没有为这两个字段设置什么。如何使用我的证书文件在 Java 中获取 certificateChain 值和签名值?不幸的是,我无法联系网络服务提供商以获取更多信息。我想如果我得到certificateChain 和字节数组中的签名,我可以做new String(byte[]) 并在SOAP 字段中使用该值。如何获取certificateChiainbyte[]值和签名?

我该如何解决这个问题?有什么建议吗?

【问题讨论】:

    标签: java certificate digital-signature


    【解决方案1】:

    您可能需要将您的签名编码为Base64 编码。 Base64 是处理二进制数据(如签名)最广泛使用的方法,这些数据应通过基于文本的协议(如 WDSL)进行传输。有很多很好的库可以从 Base64 编码和解码,例如 apache commonsGuava

    【讨论】:

    • Alexander,Base64 类存在于很多库(包)中,就像您提到的 apache commons、Guava 以及 com.ibm.xml.crypto.util (IBM JDK)、com.sun 中一样。 org.apache.xml.internal.security.utils 等等。如何确定要使用哪个库?当我使用多个库运行时,我看到的编码数据对于每个库都不同。我知道这取决于实现库以对数据进行编码的方式。但哪种是通用编码方法?还有如何从证书中获取证书链的 Base64 编码数据。 ?
    【解决方案2】:

    如果您使用 cert.getEncoded -> 这将返回证书值,而不是签名。你想看到你的签名所以你需要使用

    byte[] signature = cert.getSignature();
     System.out.println(Base64.encode(encoded));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 2023-03-28
      • 2014-03-30
      相关资源
      最近更新 更多