【问题标题】:How to verify xmldsig signature using java.security如何使用 java.security 验证 xmldsig 签名
【发布时间】:2018-06-07 14:58:06
【问题描述】:

我需要使用 java.security 包验证带有封装的 xml-dsig 签名的文档。 加载后,我根据 xsd 解组文档并拥有签名对象 - http://www.w3.org/2000/09/xmldsig#

然后:

@Service
public class XmlSignatureCheckerImpl implements XmlSignatureChecker {
    private static final String ENCRYPTION_ALGORITHM = "RSA";

    private static final String HASH_ENCRYPTION_ALGORITHM = "SHA1withRSA";

    @Override
    @Nullable
    public PublicKey getPublicKey(byte[] exp, byte[] mod) {
        BigInteger modulus = new BigInteger(1, mod);
        BigInteger exponent = new BigInteger(1, exp);
        RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);

        KeyFactory fact;
        try {
            fact = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
            return fact.generatePublic(rsaPubKey);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @Nullable
    public Boolean verify(byte[] message, byte[] signature, PublicKey publicKey) {
        final Signature sig;
        try {
            sig = Signature.getInstance(HASH_ENCRYPTION_ALGORITHM);
            sig.initVerify(publicKey);
            sig.update(message);
            boolean verify = sig.verify(Base64.encodeBase64Chunked(signature));
            return verify;
        } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }
}

调用getPublicKey并验证,结果我得到签名长度不匹配,如果我没有编码签名我没有不匹配,但验证也是错误的,但我使用完全有效的测试数据。放弃寻找错误,帮助我。请。 文件编码为 UFT-8。

【问题讨论】:

    标签: java xml-dsig


    【解决方案1】:

    【讨论】:

    • 好的,谢谢。提供的解决方案工作正常,我只是尝试使用 java.security 使代码更紧凑。
    • 老实说,我真的不知道如何使用 java.security 来最小化代码量,如果你能继续努力,如果你能分享解决方案,那就太好了。 )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2022-09-27
    相关资源
    最近更新 更多