I need to verify a signature in java. I get an url with multiple params, one of them is the signature (hexadecimal format). The message signed is the SHA-256 hash of the concatenation of all the other params. I also have the certificate with the public key to be used for the check. All the values I'm using for the test are given to me by an example which is supposed to be correct, I just create the concatenation string.
This is the code i run:
// signed message --> hash of concat
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update( concat.getBytes() );
byte[] message = digest.digest();
System.out.println("message length "+message.length); // --> 32
// signature belonging to the message --> checkValue
System.out.println("check value length " +checkValue.length()); // --> 512
byte[] sigBytes = checkValue.getBytes();
System.out.println("check value bytes "+sigBytes.length); // --> 512
// public certificate of the CA
File file3 = new File(certificatePath);
byte[] encCertRSA = new byte[(int) file3.length()];
FileInputStream fis3 = new FileInputStream(file3);
fis3.read(encCertRSA);
fis3.close();
InputStream is = new ByteArrayInputStream( encCertRSA );
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certRSA = (X509Certificate)f.generateCertificate(is);
certRSA.checkValidity();
PublicKey pubKeyRSA = certRSA.getPublicKey();
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(pubKeyRSA);
// supply the Signature object with the data for which a signature was generated --> hash of concat
sig.update(message);
boolean isValid = sig.verify( sigBytes );
System.out.println("The signature of the email verifies: " + isValid);
This is the error i get:
java.security.SignatureException: Signature length not correct: got 512 but was expecting 256
at sun.security.rsa.RSASignature.engineVerify(Unknown Source)
at java.security.Signature$Delegate.engineVerify(Unknown Source)
at java.security.Signature.verify(Unknown Source)
Am i doing anything wrong? I was expecting the signature to have a length of 256, not 512. I run a test doing a substring of the signature value to match the length of 256 and I don't get the error above, but the the sig.verify returns false.
if you look the code you wrote there is
System.out.println("check value bytes "+sigBytes.length); // --> "512"
and thenboolean isValid = sig.verify( sigBytes );
it looks like your sigBytes variable already has 512 as length before you check