Question

I need verify my data to data in Digital Signature,How I can compare between them. In this code verify signature which decrypt by public key and original signature.

  1. generation public key and privet key and Signature.
  2. read my data.
  3. hash this code.
  4. read signature.
  5. compare between signature and my data.//I have problem in this step I want compare between my data and signature.

     public static void verify () {
            BufferedReader in = new BufferedReader(new FileReader("EndSignatuer.txt"));
            FileInputStream keyfis = new FileInputStream("EndSignatuer.txt");
            byte[] Signen = new byte[keyfis.available()];
            keyfis.read(Signen);
            keyfis.close();
            String signatureString = new String(Signde);
            System.out.println("SignatureString:" + signatureString);
            len = Signde.length;
            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
            KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
            PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
            Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
            sig.initVerify(pubKey);
    

    }

I need:

public static void verify (byte[] mydata) {
........
sig.initVerify(mydata);
}
Was it helpful?

Solution

First, verifying a signature does NOT involve "decrypt by public key". For RSA, signing and verifying do use operations that are similar to encryption and decryption, which has confused a lot of people into describing them that way, but they are in fact different. For DSA as you are using here, and for ECDSA, the difference is greater: there is nothing resembling encryption or decryption involved, there is only signing and verifying.

Also, signatures, like many cryptographic objects, are effectively random bytes, not valid characters. Converting to a String and trying to display it will at best produce garbage, and may mess up your display. In situations where they need to be limited to valid chars (like S/MIME and XML), it is usual to convert to base64 or hex, and back to binary when needed.

That said, you're close. You start by calling sig.initVerify with the publickey, as you have. Then you call sig.update with the data, which can be a single buffer or a series of them (especially when you have more data than fits in memory at a time). Finally you call sig.verify with the signature value and it returns true or false. See http://docs.oracle.com/javase/7/docs/api/java/security/Signature.html for details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top