Key Translators

How do you store a key on disk? How do you transmit a key over a network connection? One solution is to use object serialization, as we did in the SecretWriting example in Chapter 1. It’s more common, however, simply to store or transmit the key as an array of bytes. To do this, we need a way to translate a Key object into a byte array and vice versa.

The javax.crypto.spec.SecretKeySpec , javax.crypto.SecretKeyFactory , and java.security.KeyFactory classes fill this niche. Although the last two classes are called factories, they function as translators. Let’s look at SecretKeySpec first because it’s simplest.

SecretKeySpec

The simplest way to convert an array of bytes to a secret key is the javax.crypto .spec.SecretKeySpec class. This class implements the SecretKey interface. You can create it from an array of bytes using one of the two constructors:

public SecretKeySpec(byte[] key, String algorithm)

This constructor creates a SecretKeySpec using the supplied byte array. The key will have the supplied algorithm.

public SecretKeySpec(byte[] key, int offset, int len, String algorithm)

This constructor creates a SecretKeySpec using len bytes of the supplied byte array, starting at offset. The key will have the supplied algorithm.

This class is useful for creating keys for Macs, as I demonstrate in Chapter 6. For example, the following code creates a MAC key from an array of random data:

SecureRandom sr = new SecureRandom(); byte[] keyBytes = new byte[20]; sr.nextBytes(keyBytes); ...

Get Java Cryptography now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.