I’ve been hard at work on the lastest release of PasswordSafeSWT, my Java port of the popular Win32 password manager PasswordSafe. The biggest change in the new version is a completely overhauled file crypto (which, in part, uses 256bit TwoFish in Chaining Block Cipher mode, along with some HMAC-SHA256, and some standard SHA256).

Now, I’ve never been exposed to CBC before, so it was quite an interesting bit of work. With a chaining block cipher, "each block of plaintext is XORed with the previous ciphertext block before being encrypted" … effectively chaining the whole decryption process. Sweet.

Turns out that BouncyCastle has fantastic support for all the ciphers needed in the PasswordSafe format, but getting there needs some divergency from the standard JCE mechanism I’ve been used to. Try using it with large keys outside the US, and you’ll be greeted with:

java.lang.SecurityException: Unsupported keysize or algorithm parameters		at javax.crypto.Cipher.init(DashoA6275)

I didn’t want end users to have to go through downloading unrestricted policy files for the JREs, so I figured I’d just use the lightweight crypto library that comes with Bouncy Castle and bypass the whole JCE thing entirely.

Using things outside the JCE is a liitle more work, but you can get there if you don’t mind digging through the extensive examples they ship with. My TwoFish CBC ended up like this:

TwofishEngine tfe = new TwofishEngine();cipher = new CBCBlockCipher(tfe); 	KeyParameter kp = new KeyParameter(key);ParametersWithIV piv = new ParametersWithIV(kp, IV);cipher.init(forEncryption, piv);

Then the actual crypto was a one liner…

int len1 = cipher.processBlock(input, 0, out, 0); 

All very doable. Go Bouncy Castle! You guys rock!