RSA SignatureException:签名长度不正确 [英] RSA SignatureException: Signature length not correct

查看:910
本文介绍了RSA SignatureException:签名长度不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在签名rsa签名时遇到问题。我有一个已用私钥加密的签名。但是,当尝试使用公钥验证它时出现问题。我收到以下异常:

I am having issues signing an rsa signature. I have a signature that has been encrypted with a private key. I have an issue when trying to validate it with the public key however. I get the following exception:

java.security.SignatureException: Signature length not correct: got 336 but was expecting 128
    at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:189)
    at java.security.Signature$Delegate.engineVerify(Signature.java:1219)
    at java.security.Signature.verify(Signature.java:652)
    at XmlReader.main(XmlReader.java:65)

我已经通过以下方式检索了我的签名和公钥:

I have retrieved my signature and public key the following way:

    BigInteger modulus = new BigInteger(Base64.getDecoder().decode(publicKeyString));
    BigInteger exponent = new BigInteger(Base64.getDecoder().decode("AQAB"));

    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);

    byte[] sigToVerify = Base64.getDecoder().decode(signatureString);
    Signature sig = Signature.getInstance("MD5WithRSA");
    sig.initVerify(pubKey);
    boolean verifies = sig.verify(sigToVerify);

应用程序在最后一行失败。对导致异常的原因有何想法?

The application fails at the last line. Any thoughts as to where this exception is caused?

更新:

已添加要验证签名的数据:

Added data for signature to be verified:

        String data = "...." //hidden since sensitive data
        byte[] dataBytes = Base64.getEncoder().encode(data.getBytes());
        dataBytes = Base64.getDecoder().decode(dataBytes);


推荐答案

在调用 sig.verify之前(sigToVerify)您应该致电

sig.update(data);

传递您要验证签名的数据。

passing the data you're verifying signature for.

并确保在参数中调用 verify 仅具有签名字节。

And make sure that calling verify in your argument you have signature bytes only.

这篇关于RSA SignatureException:签名长度不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆