1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.directory.server.kerberos.shared.crypto.encryption;
21
22
23 import java.security.NoSuchAlgorithmException;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.Map;
28 import java.util.Set;
29
30 import javax.crypto.KeyGenerator;
31 import javax.crypto.SecretKey;
32
33 import org.apache.directory.server.kerberos.shared.exceptions.ErrorType;
34 import org.apache.directory.server.kerberos.shared.exceptions.KerberosException;
35 import org.apache.directory.server.kerberos.shared.messages.value.EncryptionKey;
36
37
38
39
40
41
42
43
44
45
46 public class RandomKeyFactory
47 {
48
49 private static final Map<EncryptionType, String> DEFAULT_CIPHERS;
50
51 static
52 {
53 Map<EncryptionType, String> map = new HashMap<EncryptionType, String>();
54
55 map.put( EncryptionType.DES_CBC_MD5, "DES" );
56 map.put( EncryptionType.DES3_CBC_SHA1_KD, "DESede" );
57 map.put( EncryptionType.RC4_HMAC, "RC4" );
58 map.put( EncryptionType.AES128_CTS_HMAC_SHA1_96, "AES" );
59 map.put( EncryptionType.AES256_CTS_HMAC_SHA1_96, "AES" );
60
61 DEFAULT_CIPHERS = Collections.unmodifiableMap( map );
62 }
63
64
65
66
67
68
69
70
71 public static Map<EncryptionType, EncryptionKey> getRandomKeys() throws KerberosException
72 {
73 return getRandomKeys( DEFAULT_CIPHERS.keySet() );
74 }
75
76
77
78
79
80
81
82
83
84 public static Map<EncryptionType, EncryptionKey> getRandomKeys( Set<EncryptionType> ciphers )
85 throws KerberosException
86 {
87 Map<EncryptionType, EncryptionKey> map = new HashMap<EncryptionType, EncryptionKey>();
88
89 Iterator<EncryptionType> it = ciphers.iterator();
90 while ( it.hasNext() )
91 {
92 EncryptionType type = it.next();
93 map.put( type, getRandomKey( type ) );
94 }
95
96 return map;
97 }
98
99
100
101
102
103
104
105
106
107
108 public static EncryptionKey getRandomKey( EncryptionType encryptionType ) throws KerberosException
109 {
110 String algorithm = DEFAULT_CIPHERS.get( encryptionType );
111
112 if ( algorithm == null )
113 {
114 throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, encryptionType.getName()
115 + " is not a supported encryption type." );
116 }
117
118 try
119 {
120 KeyGenerator keyGenerator = KeyGenerator.getInstance( algorithm );
121
122 if ( encryptionType.equals( EncryptionType.AES128_CTS_HMAC_SHA1_96 ) )
123 {
124 keyGenerator.init( 128 );
125 }
126
127 if ( encryptionType.equals( EncryptionType.AES256_CTS_HMAC_SHA1_96 ) )
128 {
129 keyGenerator.init( 256 );
130 }
131
132 SecretKey key = keyGenerator.generateKey();
133
134 byte[] keyBytes = key.getEncoded();
135
136 return new EncryptionKey( encryptionType, keyBytes );
137 }
138 catch ( NoSuchAlgorithmException nsae )
139 {
140 throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, nsae );
141 }
142 }
143 }