1 /*
2  * @(#) $Id: SignatureTest.java,v 1.2 2003/07/08 08:13:52 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10import java.security.KeyPairGenerator;
11import java.security.KeyPair;
12import java.security.PublicKey;
13import java.security.PrivateKey;
14import java.security.Signature;
15import java.security.SignatureException;
16import java.security.NoSuchAlgorithmException;
17import java.security.InvalidKeyException;
18import java.io.FileInputStream;
19import java.io.IOException;
20
21public class SignatureTest {
22    private static byte[] sign(String datafile, PrivateKey prvKey, String sigAlg) throws
23            IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException {
24        Signature sig = Signature.getInstance(sigAlg);
25        sig.initSign(prvKey);
26        FileInputStream fis = new FileInputStream(datafile);
27        byte[] dataBytes = new byte[1024];
28        int nread = fis.read(dataBytes);
29        while (nread > 0) {
30            sig.update(dataBytes, 0, nread);
31            nread = fis.read(dataBytes);
32        };
33        return sig.sign();
34    }
35    private static boolean verify(String datafile, PublicKey pubKey, String sigAlg, byte[] sigbytes) throws
36            IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException {
37        Signature sig = Signature.getInstance(sigAlg);
38        sig.initVerify(pubKey);
39        FileInputStream fis = new FileInputStream(datafile);
40        byte[] dataBytes = new byte[1024];
41        int nread = fis.read(dataBytes);
42        while (nread > 0) {
43            sig.update(dataBytes, 0, nread);
44            nread = fis.read(dataBytes);
45        };
46        return sig.verify(sigbytes);
47    }
48    public static void main(String[] unused) throws Exception {
49        // Generate a key-pair
50        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
51        kpg.initialize(512); // 512 is the keysize.
52        KeyPair kp = kpg.generateKeyPair();
53        PublicKey pubk = kp.getPublic();
54        PrivateKey prvk = kp.getPrivate();
55
56        String datafile = "SignatureTest.java";
57        byte[] sigbytes = sign(datafile, prvk, "SHAwithDSA");
58        System.out.println("Signature(in hex):: " + Util.byteArray2Hex(sigbytes));
59
60        boolean result = verify(datafile, pubk, "SHAwithDSA", sigbytes);
61        System.out.println("Signature Verification Result = " + result);
62    }
63}