Wrapping and Unwrapping Keys

Wrapping a key enables secure transfer of the key from one place to another.

The wrap/unwrap API makes it more convenient to write code because it works with key objects directly. These methods also enable the possibility of a secure transfer of hardware-based keys.

To wrap a Key, first initialize the Cipher object for WRAP_MODE, and then call the following:

public final byte[] wrap(Key key);

If you are supplying the wrapped key bytes (the result of calling wrap) to someone else who will unwrap them, be sure to also send additional information that the recipient will need in order to do the unwrap:

  • the name of the key algorithm, and
  • the type of the wrapped key (one of SECRET_KEY, PRIVATE_KEY, or PUBLIC_KEY).

The key algorithm name can be determined by calling the getAlgorithm method from the Key interface:

public String getAlgorithm();

To unwrap the bytes returned by a previous call to wrap, first initialize a Cipher object for UNWRAP_MODE, then call the following:

public final Key unwrap(byte[] wrappedKey,
String wrappedKeyAlgorithm,
int wrappedKeyType));

Here, wrappedKey is the bytes returned from the previous call to wrap, wrappedKeyAlgorithm is the algorithm associated with the wrapped key, and wrappedKeyType is the type of the wrapped key. This value must be one of SECRET_KEY, PRIVATE_KEY, or PUBLIC_KEY.