Thursday, 19 February 2009

Manual Deployment Antipattern

It always felt wrong and now I found that it is actually a named antipattern! Yay! Now I can take that and use it to knock people on the head. Intellectual bullying - I'm lovin' it!

Alright, the article is about deployment automation, and this one in particular brings back memories. Hours and hours spent, manually deploying and redeploying a system, trying to ensure all dependencies were met.

Oh and of course, the reason I am loving this is the Antipatterns book, which I thought was brilliant. The whole concept of common pitfalls is just great - read it and you already know things you should be avoiding, you don't have to learn the hard way.

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!"));
    }
}