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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With