Generating Keys

Java’s security API provides two standard engines to generate keys: one to generate a pair of asymmetric keys and one to generate a secret key.

The KeyPairGenerator Class

Generation of public and private keys is provided by the KeyPairGenerator class (java.security.KeyPairGenerator):

public abstract class KeyPairGenerator extends KeyPairGeneratorSpi

Generate and provide information about public/private key pairs.

Generating a key pair is a very time-consuming operation. Fortunately, it does not need to be performed often; much of the time, we obtain keys from a key management system rather than generating them. However, when we establish our own key management system in the next chapter, we’ll need to use this class; it is often easier to generate your own keys from scratch rather than use a key management system as well.

Using the KeyPairGenerator class

Like all engine classes, the KeyPairGenerator is an abstract class for which there is no implementation in the core API. However, it is possible to retrieve instances of the KeyPairGenerator class via these methods:

public static KeyPairGenerator getInstance(String algorithm)public static KeyPairGenerator getInstance(String algorithm, String provider)

Find the implementation of the engine that generates key pairs with the named algorithm. The algorithm should be one of the standard API algorithm names; if an appropriate implementation cannot be found, this method throws a NoSuchAlgorithmException .

The first format ...

Get Java Security, 2nd Edition now with O’Reilly online learning.

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