Monday, 16 February 2009

Digital signatures in Java

We needed this for work, so while learning I wrote this very small program.

package digisign;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/*
 * http://java.sun.com/docs/books/tutorial/security/apisign/index.html
 */
public class Main {
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException {
// create some keys
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

// sign some data
byte[] data = "Hello, world!\n".getBytes();
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
signature.update(data);
byte[] sign = signature.sign();

// serialize public key and hand it over
byte[] pubKey = publicKey.getEncoded();
// store to disk, read in etc...
X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(encodedKeySpec);

// verify signature
signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(publicKey);
signature.update(data);
boolean b = signature.verify(sign);

System.out.println("signature " + (b ? "ok." : "invalid!"));
    }
}

1 comment:

Amelia said...

Thanks for sharing this source code that is used to verify a digital signature. I tried to interpret each and every line of code that you have posted and find it very useful. Now I wanted to run the code to check if it really works or not.
pdf digital signature