Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA SignatureException: Signature length not correct

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?

UPDATE:

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);
like image 665
VMA92 Avatar asked Sep 19 '25 17:09

VMA92


1 Answers

Before calling sig.verify(sigToVerify) you should call

sig.update(data);

passing the data you're verifying signature for.

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

like image 140
algrid Avatar answered Sep 21 '25 08:09

algrid