blob: bd09447c189133a389c607f7135ed5b02b4b0a3e [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26package sun.security.pkcs11;
27
28import java.util.*;
29
30import java.security.*;
31import java.security.spec.*;
32
33import javax.crypto.*;
34import javax.crypto.spec.*;
35
36import static sun.security.pkcs11.TemplateManager.*;
37import sun.security.pkcs11.wrapper.*;
38import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
39
40/**
41 * SecretKeyFactory implementation class. This class currently supports
42 * DES, DESede, AES, ARCFOUR, and Blowfish.
43 *
44 * @author Andreas Sterbenz
45 * @since 1.5
46 */
47final class P11SecretKeyFactory extends SecretKeyFactorySpi {
48
49 // token instance
50 private final Token token;
51
52 // algorithm name
53 private final String algorithm;
54
55 P11SecretKeyFactory(Token token, String algorithm) {
56 super();
57 this.token = token;
58 this.algorithm = algorithm;
59 }
60
61 private static final Map<String,Long> keyTypes;
62
63 static {
64 keyTypes = new HashMap<String,Long>();
65 addKeyType("RC4", CKK_RC4);
66 addKeyType("ARCFOUR", CKK_RC4);
67 addKeyType("DES", CKK_DES);
68 addKeyType("DESede", CKK_DES3);
69 addKeyType("AES", CKK_AES);
70 addKeyType("Blowfish", CKK_BLOWFISH);
71
72 // we don't implement RC2 or IDEA, but we want to be able to generate
73 // keys for those SSL/TLS ciphersuites.
74 addKeyType("RC2", CKK_RC2);
75 addKeyType("IDEA", CKK_IDEA);
76
77 addKeyType("TlsPremasterSecret", PCKK_TLSPREMASTER);
78 addKeyType("TlsRsaPremasterSecret", PCKK_TLSRSAPREMASTER);
79 addKeyType("TlsMasterSecret", PCKK_TLSMASTER);
80 addKeyType("Generic", CKK_GENERIC_SECRET);
81 }
82
83 private static void addKeyType(String name, long id) {
84 Long l = Long.valueOf(id);
85 keyTypes.put(name, l);
86 keyTypes.put(name.toUpperCase(Locale.ENGLISH), l);
87 }
88
89 static long getKeyType(String algorithm) {
90 Long l = keyTypes.get(algorithm);
91 if (l == null) {
92 algorithm = algorithm.toUpperCase(Locale.ENGLISH);
93 l = keyTypes.get(algorithm);
94 if (l == null) {
95 if (algorithm.startsWith("HMAC")) {
96 return PCKK_HMAC;
97 } else if (algorithm.startsWith("SSLMAC")) {
98 return PCKK_SSLMAC;
99 }
100 }
101 }
102 return (l != null) ? l.longValue() : -1;
103 }
104
105 /**
106 * Convert an arbitrary key of algorithm into a P11Key of provider.
107 * Used engineTranslateKey(), P11Cipher.init(), and P11Mac.init().
108 */
109 static P11Key convertKey(Token token, Key key, String algorithm)
110 throws InvalidKeyException {
111 token.ensureValid();
112 if (key == null) {
113 throw new InvalidKeyException("Key must not be null");
114 }
115 if (key instanceof SecretKey == false) {
116 throw new InvalidKeyException("Key must be a SecretKey");
117 }
118 long algorithmType;
119 if (algorithm == null) {
120 algorithm = key.getAlgorithm();
121 algorithmType = getKeyType(algorithm);
122 } else {
123 algorithmType = getKeyType(algorithm);
124 long keyAlgorithmType = getKeyType(key.getAlgorithm());
125 if (algorithmType != keyAlgorithmType) {
126 if ((algorithmType == PCKK_HMAC) || (algorithmType == PCKK_SSLMAC)) {
127 // ignore key algorithm for MACs
128 } else {
129 throw new InvalidKeyException
130 ("Key algorithm must be " + algorithm);
131 }
132 }
133 }
134 if (key instanceof P11Key) {
135 P11Key p11Key = (P11Key)key;
136 if (p11Key.token == token) {
137 return p11Key;
138 }
139 }
140 P11Key p11Key = token.secretCache.get(key);
141 if (p11Key != null) {
142 return p11Key;
143 }
144 if ("RAW".equals(key.getFormat()) == false) {
145 throw new InvalidKeyException("Encoded format must be RAW");
146 }
147 byte[] encoded = key.getEncoded();
148 p11Key = createKey(token, encoded, algorithm, algorithmType);
149 token.secretCache.put(key, p11Key);
150 return p11Key;
151 }
152
153 static void fixDESParity(byte[] key, int offset) {
154 for (int i = 0; i < 8; i++) {
155 int b = key[offset] & 0xfe;
156 b |= (Integer.bitCount(b) & 1) ^ 1;
157 key[offset++] = (byte)b;
158 }
159 }
160
161 private static P11Key createKey(Token token, byte[] encoded,
162 String algorithm, long keyType) throws InvalidKeyException {
163 int n = encoded.length;
164 int keyLength;
165 switch ((int)keyType) {
166 case (int)CKK_RC4:
167 if ((n < 5) || (n > 128)) {
168 throw new InvalidKeyException
169 ("ARCFOUR key length must be between 5 and 128 bytes");
170 }
171 keyLength = n << 3;
172 break;
173 case (int)CKK_DES:
174 if (n != 8) {
175 throw new InvalidKeyException
176 ("DES key length must be 8 bytes");
177 }
178 keyLength = 56;
179 fixDESParity(encoded, 0);
180 break;
181 case (int)CKK_DES3:
182 if (n == 16) {
183 keyType = CKK_DES2;
184 } else if (n == 24) {
185 keyType = CKK_DES3;
186 fixDESParity(encoded, 16);
187 } else {
188 throw new InvalidKeyException
189 ("DESede key length must be 16 or 24 bytes");
190 }
191 fixDESParity(encoded, 0);
192 fixDESParity(encoded, 8);
193 keyLength = n * 7;
194 break;
195 case (int)CKK_AES:
196 if ((n != 16) && (n != 24) && (n != 32)) {
197 throw new InvalidKeyException
198 ("AES key length must be 16, 24, or 32 bytes");
199 }
200 keyLength = n << 3;
201 break;
202 case (int)CKK_BLOWFISH:
203 if ((n < 5) || (n > 56)) {
204 throw new InvalidKeyException
205 ("Blowfish key length must be between 5 and 56 bytes");
206 }
207 keyLength = n << 3;
208 break;
209 case (int)CKK_GENERIC_SECRET:
210 case (int)PCKK_TLSPREMASTER:
211 case (int)PCKK_TLSRSAPREMASTER:
212 case (int)PCKK_TLSMASTER:
213 keyType = CKK_GENERIC_SECRET;
214 keyLength = n << 3;
215 break;
216 case (int)PCKK_SSLMAC:
217 case (int)PCKK_HMAC:
218 if (n == 0) {
219 throw new InvalidKeyException
220 ("MAC keys must not be empty");
221 }
222 keyType = CKK_GENERIC_SECRET;
223 keyLength = n << 3;
224 break;
225 default:
226 throw new InvalidKeyException("Unknown algorithm " + algorithm);
227 }
228 Session session = null;
229 try {
230 CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] {
231 new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
232 new CK_ATTRIBUTE(CKA_KEY_TYPE, keyType),
233 new CK_ATTRIBUTE(CKA_VALUE, encoded),
234 };
235 attributes = token.getAttributes
236 (O_IMPORT, CKO_SECRET_KEY, keyType, attributes);
237 session = token.getObjSession();
238 long keyID = token.p11.C_CreateObject(session.id(), attributes);
239 P11Key p11Key = (P11Key)P11Key.secretKey
240 (session, keyID, algorithm, keyLength, attributes);
241 return p11Key;
242 } catch (PKCS11Exception e) {
243 throw new InvalidKeyException("Could not create key", e);
244 } finally {
245 token.releaseSession(session);
246 }
247 }
248
249 // see JCE spec
250 protected SecretKey engineGenerateSecret(KeySpec keySpec)
251 throws InvalidKeySpecException {
252 token.ensureValid();
253 if (keySpec == null) {
254 throw new InvalidKeySpecException("KeySpec must not be null");
255 }
256 if (keySpec instanceof SecretKeySpec) {
257 try {
258 Key key = convertKey(token, (SecretKey)keySpec, algorithm);
259 return (SecretKey)key;
260 } catch (InvalidKeyException e) {
261 throw new InvalidKeySpecException(e);
262 }
263 } else if (algorithm.equalsIgnoreCase("DES")) {
264 if (keySpec instanceof DESKeySpec) {
265 byte[] keyBytes = ((DESKeySpec)keySpec).getKey();
266 keySpec = new SecretKeySpec(keyBytes, "DES");
267 return engineGenerateSecret(keySpec);
268 }
269 } else if (algorithm.equalsIgnoreCase("DESede")) {
270 if (keySpec instanceof DESedeKeySpec) {
271 byte[] keyBytes = ((DESedeKeySpec)keySpec).getKey();
272 keySpec = new SecretKeySpec(keyBytes, "DESede");
273 return engineGenerateSecret(keySpec);
274 }
275 }
276 throw new InvalidKeySpecException
277 ("Unsupported spec: " + keySpec.getClass().getName());
278 }
279
280 private byte[] getKeyBytes(SecretKey key) throws InvalidKeySpecException {
281 try {
282 key = engineTranslateKey(key);
283 if ("RAW".equals(key.getFormat()) == false) {
284 throw new InvalidKeySpecException
285 ("Could not obtain key bytes");
286 }
287 byte[] k = key.getEncoded();
288 return k;
289 } catch (InvalidKeyException e) {
290 throw new InvalidKeySpecException(e);
291 }
292 }
293
294 // see JCE spec
295 protected KeySpec engineGetKeySpec(SecretKey key, Class keySpec)
296 throws InvalidKeySpecException {
297 token.ensureValid();
298 if ((key == null) || (keySpec == null)) {
299 throw new InvalidKeySpecException
300 ("key and keySpec must not be null");
301 }
302 if (SecretKeySpec.class.isAssignableFrom(keySpec)) {
303 return new SecretKeySpec(getKeyBytes(key), algorithm);
304 } else if (algorithm.equalsIgnoreCase("DES")) {
305 try {
306 if (DESKeySpec.class.isAssignableFrom(keySpec)) {
307 return new DESKeySpec(getKeyBytes(key));
308 }
309 } catch (InvalidKeyException e) {
310 throw new InvalidKeySpecException(e);
311 }
312 } else if (algorithm.equalsIgnoreCase("DESede")) {
313 try {
314 if (DESedeKeySpec.class.isAssignableFrom(keySpec)) {
315 return new DESedeKeySpec(getKeyBytes(key));
316 }
317 } catch (InvalidKeyException e) {
318 throw new InvalidKeySpecException(e);
319 }
320 }
321 throw new InvalidKeySpecException
322 ("Unsupported spec: " + keySpec.getName());
323 }
324
325 // see JCE spec
326 protected SecretKey engineTranslateKey(SecretKey key)
327 throws InvalidKeyException {
328 return (SecretKey)convertKey(token, key, algorithm);
329 }
330
331}