Ashish Agarwal
Ashish Agarwal

Reputation: 6283

signature.verify() Always returns False?

I found 2 similar questions and tried to run the code given as solution as those said answers are not working out for me so raising the question with snippet of code.

  1. signature.verify() Always returns False
  2. Signature.verify() is always returning false

Both's said answer is not working so please DONT treat this question as DUPLICATE

here is my code.

import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.FileInputStream;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import xmlread.ReadXMLFile;


public class CertificateTest {


    public static void main(String[] sdd)  {

        try{
        FileInputStream fin = new FileInputStream("pub.arm");
        CertificateFactory f = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) f.generateCertificate(fin);
        PublicKey pk = certificate.getPublicKey();
        byte[] sign = "Qn/rlJRdZAdlPpu1UmmjE+rup8rv8d6XlS9MngAorzYDXefw0vWEP4eHil3YHoA1JUkoQQOgmw0w0QZFmrQbS33sa2t76iuqXI7EtnAPU798K+hEXP88tsYDWJNJFo9DdhkGltP5dQ02DN030Q1w58aTF+yZFfY1KVOPx2bIoL8=".getBytes();

        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(pk);
        sig.update(Base64.decode(ReadXMLFile.getString().getBytes()));

        boolean verifies = sig.verify(Base64.decode(ReadXMLFile.getString().getBytes()));

        System.out.println("signature verifies: " + verifies);

        }catch(Exception ex){}
    }
}

Upvotes: 1

Views: 5050

Answers (1)

obataku
obataku

Reputation: 29636

Below is the explanation before I knew that ReadXMLFile.getString was not the data whose integrity was being tested but rather the encoded signature itself. See our discussion for the resolution!


Your code is wrong -- you're trying to compare the RSA-encrypted SHA1 digest of the base64-decoded ReadXMLFile.getString() to itself.

final byte[] data = Base64.decode(ReadXMLFile.getString().getBytes());
sig.update(data);
boolean verifies = sig.verify(data);

From the specification for Signature.update:

Updates the data to be signed or verified, using the specified array of bytes.

Then, from Signature.verify:

Verifies the passed-in signature.

Now, you're not actually passing the signature data into verify! Did you mean to do sig.verify(Base64.decode(sign)) instead?

If you need further proof, post pub.arm and I can demonstrate working, correct code :-)

Upvotes: 1

Related Questions