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.EnumMap;
26 import java.util.HashMap;
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.i18n.I18n;
34 import org.apache.directory.shared.kerberos.codec.types.EncryptionType;
35 import org.apache.directory.shared.kerberos.components.EncryptionKey;
36 import org.apache.directory.shared.kerberos.exceptions.ErrorType;
37 import org.apache.directory.shared.kerberos.exceptions.KerberosException;
38
39
40
41
42
43
44
45
46
47 public class RandomKeyFactory
48 {
49
50 private static final Map<EncryptionType, String> DEFAULT_CIPHERS;
51
52 static
53 {
54 EnumMap<EncryptionType, String> map = new EnumMap<>( EncryptionType.class );
55
56 map.put( EncryptionType.DES_CBC_MD5, "DES" );
57 map.put( EncryptionType.DES3_CBC_SHA1_KD, "DESede" );
58 map.put( EncryptionType.RC4_HMAC, "RC4" );
59 map.put( EncryptionType.AES128_CTS_HMAC_SHA1_96, "AES" );
60 map.put( EncryptionType.AES256_CTS_HMAC_SHA1_96, "AES" );
61
62 DEFAULT_CIPHERS = Collections.unmodifiableMap( map );
63 }
64
65
66
67
68
69
70
71
72 public static Map<EncryptionType, EncryptionKey> getRandomKeys() throws KerberosException
73 {
74 return getRandomKeys( DEFAULT_CIPHERS.keySet() );
75 }
76
77
78
79
80
81
82
83
84
85 public static Map<EncryptionType, EncryptionKey> getRandomKeys( Set<EncryptionType> ciphers )
86 throws KerberosException
87 {
88 Map<EncryptionType, EncryptionKey> map = new HashMap<>();
89
90 for ( EncryptionType encryptionType : ciphers )
91 {
92 map.put( encryptionType, getRandomKey( encryptionType ) );
93 }
94
95 return map;
96 }
97
98
99
100
101
102
103
104
105
106
107 public static EncryptionKey getRandomKey( EncryptionType encryptionType ) throws KerberosException
108 {
109 String algorithm = DEFAULT_CIPHERS.get( encryptionType );
110
111 if ( algorithm == null )
112 {
113 throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, I18n.err( I18n.ERR_616,
114 encryptionType.getName() ) );
115 }
116
117 try
118 {
119 KeyGenerator keyGenerator = KeyGenerator.getInstance( algorithm );
120
121 if ( encryptionType.equals( EncryptionType.AES128_CTS_HMAC_SHA1_96 ) )
122 {
123 keyGenerator.init( 128 );
124 }
125
126 if ( encryptionType.equals( EncryptionType.AES256_CTS_HMAC_SHA1_96 ) )
127 {
128 keyGenerator.init( 256 );
129 }
130
131 SecretKey key = keyGenerator.generateKey();
132
133 byte[] keyBytes = key.getEncoded();
134
135 return new EncryptionKey( encryptionType, keyBytes );
136 }
137 catch ( NoSuchAlgorithmException nsae )
138 {
139 throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, nsae );
140 }
141 }
142 }