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
SecretKeySpecusing 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
SecretKeySpecusinglenbytes of the supplied byte array, starting atoffset. 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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access