Mega Code Archive

 
Categories / Java / Security
 

VerifySignature

package com.ack.security; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import com.ack.security.ByteUtils; /* Verify a DSA signature */ class VerifySignature { public static void main( String[] args ) throws Exception { final String publicKeyFile = "hello.pubkey"; final String signedDataFile = "hello.sig"; final String unsignedDataFile = "hello.txt"; // import the public key byte[] encKey = com.ack.security.ByteUtils.loadBytesFromFile( publicKeyFile ); // start up the key fatory System.out.println( "start up the key factory..." ); java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance( "DSA", "SUN" ); // get hold of the public key java.security.spec.X509EncodedKeySpec pubKeySpec = new java.security.spec.X509EncodedKeySpec( encKey ); java.security.PublicKey pubKey = keyFactory.generatePublic( pubKeySpec ); System.out.println( "got the public key" ); // load the signed data byte[] sigToVerify = com.ack.security.ByteUtils.loadBytesFromFile( signedDataFile ); System.out.println( "loaded the signed data..." ); // create a signature object with the supplied public key java.security.Signature sig = java.security.Signature.getInstance( "SHA1withDSA", "SUN" ); sig.initVerify( pubKey ); System.out.println( "create a signature with supplied public key" ); // load original data into the signature byte[] buffer = com.ack.security.ByteUtils.loadBytesFromFile( unsignedDataFile ); sig.update( buffer ); System.out.println( "loaded original data into the signature" ); // verify the two signatures System.out.println( "about to verity signed data with newly created signature" ); boolean verifies = sig.verify( sigToVerify ); System.out.println( "signature verifies: " + verifies ); } }