Generate and verify RSA signature in Java 

Joined:
04/09/2007
Posts:
784

November 01, 2013 10:23:45    Last update: November 01, 2013 10:23:45
This example class generates and verifies RSA signature on a test file.
import java.io.*;
import java.security.*;
import java.security.spec.*;

public class VerifyRSASig {
    public static void main(String[] args) throws Exception {
	byte[] sig = genSignature(new File("CSSBeforeAfter.html"));
	System.out.println("Sig length: " + sig.length);
	System.out.println("Signature:\n" + toHexString(sig));
	System.out.println("Signature (num):\n" + new java.math.BigInteger(sig));
	System.out.println("Signature valid: " + checkSignature(sig, new File("CSSBeforeAfter.html")));
    }

    private static byte[] genSignature(File input) throws Exception {
	Signature s = Signature.getInstance("SHA256withRSA");
	s.initSign(getPrivateKey());

	byte[] buffer = new byte[1024];
	InputStream in = new FileInputStream(input);
	int n;
	while ((n = in.read(buffer)) >= 0) {
	    s.update(buffer, 0, n);
	}
	in.close();

	return s.sign();
    }

    private static boolean checkSignature(byte[] sig, File input) throws Exception {
	Signature s = Signature.getInstance("SHA256withRSA");
	s.initVerify(getPublicKey());

	byte[] buffer = new byte[1024];
	InputStream in = new FileInputStream(input);
	int n;
	while ((n = in.read(buffer)) >= 0) {
	    s.update(buffer, 0, n);
	}
	in.close();

	return s.verify(sig);
    }
    .
    .
    .
    // getPrivateKey(), getPublicKey(), toHexString() omitted.
}
Share |
| Comment  | Tags