9.7.2. Key Generation

To encrypt, you need to generate a key. Each cipher has a different format for keys, and you need to make sure that the key generation is random. Follow these steps:

1. Get a KeyGenerator for your algorithm.

2. Initialize the generator with a source for randomness. If the block length of the cipher is variable, also specify the desired block length.

3. Call the generateKey method.

For example, here is how you generate an AES key:

KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); // see below keygen.init(random); Key key = keygen.generateKey();

Alternatively, you can produce a key from a fixed set of raw data (perhaps derived from a password or the ...

Get Core Java® Volume II—Advanced Features, Ninth Edition now with O’Reilly online learning.

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