DESedeKeyGenerator.java revision e6bf3e8dfa2804891a82075cb469b736321b4827
1package org.bouncycastle.crypto.generators;
2
3import org.bouncycastle.crypto.KeyGenerationParameters;
4import org.bouncycastle.crypto.params.DESedeParameters;
5
6public class DESedeKeyGenerator
7    extends DESKeyGenerator
8{
9    /**
10     * initialise the key generator - if strength is set to zero
11     * the key generated will be 192 bits in size, otherwise
12     * strength can be 128 or 192 (or 112 or 168 if you don't count
13     * parity bits), depending on whether you wish to do 2-key or 3-key
14     * triple DES.
15     *
16     * @param param the parameters to be used for key generation
17     */
18    public void init(
19        KeyGenerationParameters param)
20    {
21        this.random = param.getRandom();
22        this.strength = (param.getStrength() + 7) / 8;
23
24        if (strength == 0 || strength == (168 / 8))
25        {
26            strength = DESedeParameters.DES_EDE_KEY_LENGTH;
27        }
28        else if (strength == (112 / 8))
29        {
30            strength = 2 * DESedeParameters.DES_KEY_LENGTH;
31        }
32        else if (strength != DESedeParameters.DES_EDE_KEY_LENGTH
33                && strength != (2 * DESedeParameters.DES_KEY_LENGTH))
34        {
35            throw new IllegalArgumentException("DESede key must be "
36                + (DESedeParameters.DES_EDE_KEY_LENGTH * 8) + " or "
37                + (2 * 8 * DESedeParameters.DES_KEY_LENGTH)
38                + " bits long.");
39        }
40    }
41
42    public byte[] generateKey()
43    {
44        byte[]  newKey = new byte[strength];
45
46        do
47        {
48            random.nextBytes(newKey);
49
50            DESedeParameters.setOddParity(newKey);
51        }
52        while (DESedeParameters.isWeakKey(newKey, 0, newKey.length));
53
54        return newKey;
55    }
56}
57