]> git.saurik.com Git - apple/security.git/blob - OSX/sec/Security/SecRSAKey.c
Security-57740.31.2.tar.gz
[apple/security.git] / OSX / sec / Security / SecRSAKey.c
1 /*
2 * Copyright (c) 2006-2010,2012-2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * SecRSAKey.c - CoreFoundation based rsa key object
26 */
27
28
29 #include "SecRSAKey.h"
30 #include "SecRSAKeyPriv.h"
31 #include <Security/SecKeyInternal.h>
32 #include <Security/SecItem.h>
33 #include <Security/SecBasePriv.h>
34 #include <AssertMacros.h>
35 #include <Security/SecureTransport.h> /* For error codes. */
36 #include <CoreFoundation/CFData.h> /* For error codes. */
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <unistd.h>
40 #include <CoreFoundation/CFNumber.h>
41 #include <Security/SecFramework.h>
42 #include <Security/SecRandom.h>
43 #include <utilities/debugging.h>
44 #include <utilities/SecCFWrappers.h>
45 #include <utilities/SecCFError.h>
46 #include <utilities/array_size.h>
47 #include "SecItemPriv.h"
48 #include <Security/SecInternal.h>
49
50 #include <corecrypto/ccn.h>
51 #include <corecrypto/ccrsa.h>
52 #include <corecrypto/ccsha1.h>
53 #include <corecrypto/ccsha2.h>
54
55 #include <libDER/asn1Types.h>
56 #include <libDER/DER_Keys.h>
57 #include <libDER/DER_Encode.h>
58
59 #include <CommonCrypto/CommonDigest.h>
60
61 #include <corecrypto/ccrsa_priv.h>
62
63 #include <stdint.h>
64 #include <string.h>
65
66 #define kMaximumRSAKeyBits (1024 * 8)
67
68 #define RSA_PKCS1_PAD_SIGN 0x01
69 #define RSA_PKCS1_PAD_ENCRYPT 0x02
70
71 /*
72 *
73 * Public Key
74 *
75 */
76
77 /* Public key static functions. */
78 static void SecRSAPublicKeyDestroy(SecKeyRef key) {
79 /* Zero out the public key */
80 if (key->key) {
81 ccrsa_pub_ctx_t pubkey;
82 pubkey.pub = key->key;
83 cc_clear(ccrsa_pub_ctx_size(ccn_sizeof_n(ccrsa_ctx_n(pubkey))), pubkey.pub);
84 free(key->key);
85 key->key = NULL;
86 }
87 }
88
89 #define cc_skip_zeros(size, ptr) { while (size > 0 && *ptr == 0) { ++ptr; --size; } }
90
91 //
92 // pubkey is initilaized with an n which is the maximum it can hold
93 // We set the n to its correct value given m.
94 //
95 static int ccrsa_pub_init(ccrsa_pub_ctx_t pubkey,
96 size_t m_size, const uint8_t* m,
97 size_t e_size, const uint8_t* e)
98 {
99 cc_skip_zeros(m_size, m);
100
101 cc_size nm = ccn_nof_size(m_size);
102 if (nm > ccrsa_ctx_n(pubkey))
103 return -1;
104
105 ccrsa_ctx_n(pubkey) = nm;
106
107 ccn_read_uint(nm, ccrsa_ctx_m(pubkey), m_size, m);
108 cczp_init(ccrsa_ctx_zm(pubkey));
109
110 return ccn_read_uint(nm, ccrsa_ctx_e(pubkey), e_size, e);
111 }
112
113
114 static OSStatus ccrsa_pub_decode_apple(ccrsa_pub_ctx_t pubkey, size_t pkcs1_size, const uint8_t* pkcs1)
115 {
116 OSStatus result = errSecParam;
117
118 DERItem keyItem = {(DERByte *)pkcs1, pkcs1_size};
119 DERRSAPubKeyApple decodedKey;
120
121 require_noerr_action_quiet(DERParseSequence(&keyItem,
122 DERNumRSAPubKeyAppleItemSpecs, DERRSAPubKeyAppleItemSpecs,
123 &decodedKey, sizeof(decodedKey)),
124 errOut, result = errSecDecode);
125
126 // We could honor the reciprocal, but we don't think this is used enough to care.
127 // Don't bother exploding the below function to try to handle this case, it computes.
128
129 require_noerr_quiet(ccrsa_pub_init(pubkey,
130 decodedKey.modulus.length, decodedKey.modulus.data,
131 decodedKey.pubExponent.length, decodedKey.pubExponent.data),
132 errOut);
133
134 result = errSecSuccess;
135
136 errOut:
137 return result;
138 }
139
140
141 static void ccasn_encode_int(cc_size n, const cc_unit*s, size_t s_size, uint8_t **buffer)
142 {
143 **buffer = ASN1_INTEGER;
144 *buffer += 1;
145
146 DERSize itemLength = 4;
147 DEREncodeLength(s_size, *buffer, &itemLength);
148 *buffer += itemLength;
149
150 ccn_write_int(n, s, s_size, *buffer);
151
152 *buffer += s_size;
153 }
154
155
156 static OSStatus SecRSAPublicKeyInit(SecKeyRef key,
157 const uint8_t *keyData, CFIndex keyDataLength, SecKeyEncoding encoding) {
158
159 OSStatus result = errSecParam;
160 ccrsa_pub_ctx_t pubkey;
161 size_t size_n = 0;
162
163 switch (encoding) {
164 case kSecKeyEncodingBytes: // Octets is PKCS1
165 case kSecKeyEncodingPkcs1: {
166 size_n = ccrsa_import_pub_n(keyDataLength, keyData);
167 require_quiet(size_n != 0, errOut);
168 require_quiet(size_n <= ccn_nof(kMaximumRSAKeyBits), errOut);
169
170 key->key = calloc(1, ccrsa_pub_ctx_size(ccn_sizeof_n(size_n)));
171 require_action_quiet(key->key, errOut, result = errSecAllocate);
172
173 pubkey.pub = key->key;
174 ccrsa_ctx_n(pubkey) = size_n;
175
176 require_noerr_quiet(ccrsa_import_pub(pubkey, keyDataLength, keyData), errOut);
177
178 result = errSecSuccess;
179
180 break;
181 }
182 case kSecKeyEncodingApplePkcs1:
183 /* for the few uses (I can't find any) that uses kSecKeyEncodingApplePkcs1, force largest keys */
184 size_n = ccn_nof(kMaximumRSAKeyBits);
185
186 key->key = calloc(1, ccrsa_pub_ctx_size(ccn_sizeof_n(size_n)));
187 require_action_quiet(key->key, errOut, result = errSecAllocate);
188
189 pubkey.pub = key->key;
190 ccrsa_ctx_n(pubkey) = size_n;
191
192 result = ccrsa_pub_decode_apple(pubkey, keyDataLength, keyData);
193 break;
194 case kSecKeyEncodingRSAPublicParams:
195 {
196 SecRSAPublicKeyParams *params = (SecRSAPublicKeyParams *)keyData;
197
198 size_n = ccn_nof_size(params->modulusLength);
199
200 key->key = calloc(1, ccrsa_pub_ctx_size(ccn_sizeof_n(size_n)));
201 require_action_quiet(key->key, errOut, result = errSecAllocate);
202
203 pubkey.pub = key->key;
204 ccrsa_ctx_n(pubkey) = size_n;
205
206 require_noerr_quiet(ccrsa_pub_init(pubkey,
207 params->modulusLength, params->modulus,
208 params->exponentLength, params->exponent), errOut);
209
210 result = errSecSuccess;
211 break;
212 }
213 case kSecExtractPublicFromPrivate:
214 {
215 ccrsa_full_ctx_t fullKey;
216 fullKey.full = (ccrsa_full_ctx*) keyData;
217
218 size_n = ccrsa_ctx_n(fullKey);
219
220 key->key = calloc(1, ccrsa_pub_ctx_size(ccn_sizeof_n(size_n)));
221 require_action_quiet(key->key, errOut, result = errSecAllocate);
222
223 pubkey.pub = key->key;
224 ccrsa_ctx_n(pubkey) = size_n;
225
226 memcpy(pubkey.pub, ccrsa_ctx_public(fullKey).pub, ccrsa_pub_ctx_size(ccn_sizeof_n(size_n)));
227 result = errSecSuccess;
228 break;
229 }
230 default:
231 break;
232 }
233
234 errOut:
235 return result;
236 }
237
238 static CFTypeRef SecRSAPublicKeyCopyOperationResult(SecKeyRef key, SecKeyOperationType operation, SecKeyAlgorithm algorithm,
239 CFArrayRef allAlgorithms, SecKeyOperationMode mode,
240 CFTypeRef in1, CFTypeRef in2, CFErrorRef *error) {
241 CFTypeRef result;
242 require_action_quiet(CFEqual(algorithm, kSecKeyAlgorithmRSAEncryptionRawCCUnit), out, result = kCFNull);
243
244 ccrsa_pub_ctx_t pubkey;
245 pubkey.pub = key->key;
246 result = kCFBooleanTrue;
247 switch (operation) {
248 case kSecKeyOperationTypeEncrypt:
249 if (mode == kSecKeyOperationModePerform) {
250 // Verify that plaintext is smaller than modulus.
251 require_action_quiet(ccn_cmpn(ccn_nof_size(CFDataGetLength(in1)), (const cc_unit *)CFDataGetBytePtr(in1),
252 ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey)) < 0, out,
253 (result = NULL,
254 SecError(errSecParam, error, CFSTR("RSApubkey wrong size of buffer to encrypt"))));
255
256 // Encrypt into output buffer.
257 result = CFDataCreateMutableWithScratch(NULL, ccrsa_block_size(pubkey));
258 ccrsa_pub_crypt(pubkey, (cc_unit *)CFDataGetMutableBytePtr((CFMutableDataRef)result),
259 (const cc_unit *)CFDataGetBytePtr(in1));
260 }
261 break;
262 case kSecKeyOperationTypeDecrypt:
263 if (mode == kSecKeyOperationModePerform) {
264 // Decrypt into output buffer.
265 result = CFDataCreateMutableWithScratch(NULL, ccrsa_block_size(pubkey));
266 ccrsa_pub_crypt(pubkey, (cc_unit *)CFDataGetMutableBytePtr((CFMutableDataRef)result),
267 (const cc_unit *)CFDataGetBytePtr(in1));
268 }
269 break;
270 default:
271 result = kCFNull;
272 break;
273 }
274
275 out:
276 return result;
277 }
278
279 static size_t SecRSAPublicKeyBlockSize(SecKeyRef key) {
280 ccrsa_pub_ctx_t pubkey;
281 pubkey.pub = key->key;
282 return ccrsa_block_size(pubkey);
283 }
284
285
286 static CFDataRef SecRSAPublicKeyCreatePKCS1(CFAllocatorRef allocator, ccrsa_pub_ctx_t pubkey)
287 {
288 size_t m_size = ccn_write_int_size(ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey));
289 size_t e_size = ccn_write_int_size(ccrsa_ctx_n(pubkey), ccrsa_ctx_e(pubkey));
290
291 const size_t seq_size = DERLengthOfItem(ASN1_INTEGER, m_size) +
292 DERLengthOfItem(ASN1_INTEGER, e_size);
293
294 const size_t result_size = DERLengthOfItem(ASN1_SEQUENCE, seq_size);
295
296 CFMutableDataRef pkcs1 = CFDataCreateMutableWithScratch(allocator, result_size);
297 uint8_t *bytes = CFDataGetMutableBytePtr(pkcs1);
298
299 *bytes++ = ONE_BYTE_ASN1_CONSTR_SEQUENCE;
300
301 DERSize itemLength = 4;
302 DEREncodeLength(seq_size, bytes, &itemLength);
303 bytes += itemLength;
304
305 ccasn_encode_int(ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey), m_size, &bytes);
306 ccasn_encode_int(ccrsa_ctx_n(pubkey), ccrsa_ctx_e(pubkey), e_size, &bytes);
307
308 return pkcs1;
309 }
310
311 static OSStatus SecRSAPublicKeyCopyPublicSerialization(SecKeyRef key, CFDataRef* serialized)
312 {
313 ccrsa_pub_ctx_t pubkey;
314 pubkey.pub = key->key;
315
316 CFAllocatorRef allocator = CFGetAllocator(key);
317 *serialized = SecRSAPublicKeyCreatePKCS1(allocator, pubkey);
318
319 if (NULL == *serialized)
320 return errSecDecode;
321 else
322 return errSecSuccess;
323 }
324
325 static CFDictionaryRef SecRSAPublicKeyCopyAttributeDictionary(SecKeyRef key) {
326 CFDictionaryRef dict = SecKeyGeneratePublicAttributeDictionary(key, kSecAttrKeyTypeRSA);
327 CFMutableDictionaryRef mutableDict = CFDictionaryCreateMutableCopy(NULL, 0, dict);
328 CFDictionarySetValue(mutableDict, kSecAttrCanDecrypt, kCFBooleanTrue);
329 CFDictionarySetValue(mutableDict, kSecAttrCanDerive, kCFBooleanFalse);
330 CFAssignRetained(dict, mutableDict);
331 return dict;
332 }
333
334 static CFDataRef SecRSAPublicKeyCopyExternalRepresentation(SecKeyRef key, CFErrorRef *error) {
335 ccrsa_pub_ctx_t pubkey;
336 pubkey.pub = key->key;
337 return SecRSAPublicKeyCreatePKCS1(CFGetAllocator(key), pubkey);
338 }
339
340 static CFStringRef SecRSAPublicKeyCopyDescription(SecKeyRef key) {
341
342 CFStringRef keyDescription = NULL;
343 CFDataRef modRef = SecKeyCopyModulus(key);
344
345 ccrsa_pub_ctx_t pubkey;
346 pubkey.pub = key->key;
347
348 CFStringRef modulusString = CFDataCopyHexString(modRef);
349 require_quiet(modulusString, fail);
350
351 keyDescription = CFStringCreateWithFormat(kCFAllocatorDefault,NULL,CFSTR( "<SecKeyRef algorithm id: %lu, key type: %s, version: %d, block size: %zu bits, exponent: {hex: %llx, decimal: %lld}, modulus: %@, addr: %p>"), SecKeyGetAlgorithmId(key), key->key_class->name, key->key_class->version, (8*SecKeyGetBlockSize(key)), (long long)*ccrsa_ctx_e(pubkey), (long long)*ccrsa_ctx_e(pubkey), modulusString, key);
352
353 fail:
354 CFReleaseSafe(modRef);
355 CFReleaseSafe(modulusString);
356 if(!keyDescription)
357 keyDescription = CFStringCreateWithFormat(kCFAllocatorDefault,NULL,CFSTR("<SecKeyRef algorithm id: %lu, key type: %s, version: %d, block size: %zu bits, addr: %p>"), (long)SecKeyGetAlgorithmId(key), key->key_class->name, key->key_class->version, (8*SecKeyGetBlockSize(key)), key);
358
359 return keyDescription;
360 }
361
362 SecKeyDescriptor kSecRSAPublicKeyDescriptor = {
363 .version = kSecKeyDescriptorVersion,
364 .name = "RSAPublicKey",
365
366 .init = SecRSAPublicKeyInit,
367 .destroy = SecRSAPublicKeyDestroy,
368 .blockSize = SecRSAPublicKeyBlockSize,
369 .copyDictionary = SecRSAPublicKeyCopyAttributeDictionary,
370 .copyExternalRepresentation = SecRSAPublicKeyCopyExternalRepresentation,
371 .describe = SecRSAPublicKeyCopyDescription,
372 .copyPublic = SecRSAPublicKeyCopyPublicSerialization,
373 .copyOperationResult = SecRSAPublicKeyCopyOperationResult,
374 };
375
376 /* Public Key API functions. */
377 SecKeyRef SecKeyCreateRSAPublicKey_ios(CFAllocatorRef allocator,
378 const uint8_t *keyData, CFIndex keyDataLength,
379 SecKeyEncoding encoding) {
380 return SecKeyCreate(allocator, &kSecRSAPublicKeyDescriptor, keyData,
381 keyDataLength, encoding);
382 }
383
384 SecKeyRef SecKeyCreateRSAPublicKey(CFAllocatorRef allocator,
385 const uint8_t *keyData, CFIndex keyDataLength,
386 SecKeyEncoding encoding) {
387 return SecKeyCreateRSAPublicKey_ios(allocator, keyData,
388 keyDataLength, encoding);
389 }
390
391 CFDataRef SecKeyCopyModulus(SecKeyRef key) {
392 CFDataRef modulus = NULL;
393 if (key->key_class == &kSecRSAPublicKeyDescriptor) {
394 ccrsa_pub_ctx_t pubkey;
395 pubkey.pub = key->key;
396
397 size_t m_size = ccn_write_uint_size(ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey));
398
399 CFAllocatorRef allocator = CFGetAllocator(key);
400 CFMutableDataRef modulusData = CFDataCreateMutable(allocator, m_size);
401
402 if (modulusData == NULL)
403 return NULL;
404
405 CFDataSetLength(modulusData, m_size);
406
407 ccn_write_uint(ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey), m_size, CFDataGetMutableBytePtr(modulusData));
408 modulus = modulusData;
409 } else if (key->key_class->copyDictionary != NULL) {
410 CFDictionaryRef dict = key->key_class->copyDictionary(key);
411 if (dict != NULL) {
412 modulus = CFRetainSafe(CFDictionaryGetValue(dict, CFSTR("_rsam")));
413 CFRelease(dict);
414 }
415 }
416
417 return modulus;
418 }
419
420 CFDataRef SecKeyCopyExponent(SecKeyRef key) {
421 CFDataRef exponent = NULL;
422 if (key->key_class == &kSecRSAPublicKeyDescriptor) {
423 ccrsa_pub_ctx_t pubkey;
424 pubkey.pub = key->key;
425
426 size_t e_size = ccn_write_uint_size(ccrsa_ctx_n(pubkey), ccrsa_ctx_e(pubkey));
427
428 CFAllocatorRef allocator = CFGetAllocator(key);
429 CFMutableDataRef exponentData = CFDataCreateMutable(allocator, e_size);
430
431 if (exponentData == NULL)
432 return NULL;
433
434 CFDataSetLength(exponentData, e_size);
435
436 ccn_write_uint(ccrsa_ctx_n(pubkey), ccrsa_ctx_e(pubkey), e_size, CFDataGetMutableBytePtr(exponentData));
437 exponent = exponentData;
438 } else if (key->key_class->copyDictionary != NULL) {
439 CFDictionaryRef dict = key->key_class->copyDictionary(key);
440 if (dict != NULL) {
441 exponent = CFRetainSafe(CFDictionaryGetValue(dict, CFSTR("_rsae")));
442 CFRelease(dict);
443 }
444 }
445
446 return exponent;
447 }
448
449
450 /*
451 *
452 * Private Key
453 *
454 */
455
456 /* Private key static functions. */
457 static void SecRSAPrivateKeyDestroy(SecKeyRef key) {
458 /* Zero out the public key */
459 if (key->key) {
460 ccrsa_full_ctx_t fullkey;
461 fullkey.full = key->key;
462 cc_clear(ccrsa_full_ctx_size(ccn_sizeof_n(ccrsa_ctx_n(fullkey))), fullkey.full);
463 free(key->key);
464 key->key = NULL;
465 }
466 }
467
468 static OSStatus SecRSAPrivateKeyInit(SecKeyRef key, const uint8_t *keyData, CFIndex keyDataLength, SecKeyEncoding encoding) {
469 OSStatus result = errSecParam;
470 ccrsa_full_ctx_t fullkey;
471 cc_size size_n = 0;
472
473 switch (encoding) {
474 case kSecKeyEncodingBytes: // Octets is PKCS1
475 case kSecKeyEncodingPkcs1:
476 {
477 size_n = ccrsa_import_priv_n(keyDataLength,keyData);
478 require_quiet(size_n != 0, errOut);
479 require_quiet(size_n <= ccn_nof(kMaximumRSAKeyBits), errOut);
480
481 key->key = calloc(1, ccrsa_full_ctx_size(ccn_sizeof_n(size_n)));
482 require_action_quiet(key->key, errOut, result = errSecAllocate);
483
484 fullkey.full = key->key;
485 ccrsa_ctx_n(fullkey) = size_n;
486
487 require_quiet(ccrsa_import_priv(fullkey, keyDataLength, keyData)==0, errOut);
488
489 result = errSecSuccess;
490 break;
491 }
492 case kSecGenerateKey:
493 {
494 CFDictionaryRef parameters = (CFDictionaryRef) keyData;
495
496 CFTypeRef ksize = CFDictionaryGetValue(parameters, kSecAttrKeySizeInBits);
497 CFIndex keyLengthInBits = getIntValue(ksize);
498
499 if (keyLengthInBits < 512 || keyLengthInBits > kMaximumRSAKeyBits) {
500 secwarning("Invalid or missing key size in: %@", parameters);
501 result = errSecKeySizeNotAllowed;
502 goto errOut;
503 }
504
505 size_n = ccn_nof(keyLengthInBits);
506
507 key->key = calloc(1, ccrsa_full_ctx_size(ccn_sizeof_n(size_n)));
508 require_action_quiet(key->key, errOut, result = errSecAllocate);
509
510 fullkey.full = key->key;
511 ccrsa_ctx_n(fullkey) = size_n;
512
513 /* TODO: Add support for kSecPublicExponent parameter. */
514 static uint8_t e[] = { 0x01, 0x00, 0x01 }; // Default is 65537
515 if (!ccrsa_generate_fips186_key(keyLengthInBits, fullkey.full, sizeof(e), e, ccrng_seckey,ccrng_seckey))
516 result = errSecSuccess;
517 break;
518 }
519 default:
520 break;
521 }
522 errOut:
523 return result;
524 }
525
526 static CFTypeRef SecRSAPrivateKeyCopyOperationResult(SecKeyRef key, SecKeyOperationType operation, SecKeyAlgorithm algorithm,
527 CFArrayRef allAlgorithms, SecKeyOperationMode mode,
528 CFTypeRef in1, CFTypeRef in2, CFErrorRef *error) {
529 CFTypeRef result = kCFNull;
530
531 ccrsa_full_ctx_t fullkey = { .full = key->key };
532 switch (operation) {
533 case kSecKeyOperationTypeSign:
534 if (CFEqual(algorithm, kSecKeyAlgorithmRSASignatureRawCCUnit)) {
535 if (mode == kSecKeyOperationModePerform) {
536 // Verify that data is smaller than modulus.
537 require_action_quiet(ccn_cmpn(ccn_nof_size(CFDataGetLength(in1)), (const cc_unit *)CFDataGetBytePtr(in1),
538 ccrsa_ctx_n(fullkey), ccrsa_ctx_m(fullkey)) < 0, out,
539 (result = NULL,
540 SecError(errSecParam, error, CFSTR("%@: sign - digest too big (%d bytes)"),
541 (int)CFDataGetLength(in1))));
542
543 // Encrypt buffer and write it to output data.
544 result = CFDataCreateMutableWithScratch(kCFAllocatorDefault, ccrsa_block_size(ccrsa_ctx_public(fullkey)));
545 ccrsa_priv_crypt(fullkey, (cc_unit *)CFDataGetMutableBytePtr((CFMutableDataRef)result),
546 (const cc_unit *)CFDataGetBytePtr(in1));
547 } else {
548 // Operation is supported.
549 result = kCFBooleanTrue;
550 }
551 }
552 break;
553 case kSecKeyOperationTypeDecrypt:
554 if (CFEqual(algorithm, kSecKeyAlgorithmRSAEncryptionRawCCUnit)) {
555 if (mode == kSecKeyOperationModePerform) {
556 // Decrypt buffer and write it to output data.
557 result = CFDataCreateMutableWithScratch(NULL, ccrsa_block_size(fullkey));
558 ccrsa_priv_crypt(fullkey, (cc_unit *)CFDataGetMutableBytePtr((CFMutableDataRef)result),
559 (const cc_unit *)CFDataGetBytePtr(in1));
560 } else {
561 // Operation is supported.
562 result = kCFBooleanTrue;
563 }
564 }
565 break;
566 default:
567 break;
568 }
569
570 out:
571 return result;
572 }
573
574 static size_t SecRSAPrivateKeyBlockSize(SecKeyRef key) {
575 ccrsa_full_ctx_t fullkey;
576 fullkey.full = key->key;
577
578 return ccn_write_uint_size(ccrsa_ctx_n(fullkey), ccrsa_ctx_m(fullkey));
579 }
580
581 static CFDataRef SecRSAPrivateKeyCreatePKCS1(CFAllocatorRef allocator, ccrsa_full_ctx_t fullkey)
582 {
583 const size_t result_size = ccrsa_export_priv_size(fullkey);
584
585 CFMutableDataRef pkcs1 = CFDataCreateMutable(allocator, result_size);
586
587 if (pkcs1 == NULL)
588 return NULL;
589
590 CFDataSetLength(pkcs1, result_size);
591
592 uint8_t *bytes = CFDataGetMutableBytePtr(pkcs1);
593
594 if (ccrsa_export_priv(fullkey,result_size,bytes)!=0) {
595 /* Decoding failed */
596 CFReleaseNull(pkcs1);
597 return NULL;
598 }
599
600 return pkcs1;
601 }
602
603 static CFDataRef SecRSAPrivateKeyCopyPKCS1(SecKeyRef key)
604 {
605 ccrsa_full_ctx_t fullkey;
606 fullkey.full = key->key;
607
608 CFAllocatorRef allocator = CFGetAllocator(key);
609 return SecRSAPrivateKeyCreatePKCS1(allocator, fullkey);
610 }
611
612 static OSStatus SecRSAPrivateKeyCopyPublicSerialization(SecKeyRef key, CFDataRef* serialized)
613 {
614 ccrsa_full_ctx_t fullkey;
615 fullkey.full = key->key;
616
617 CFAllocatorRef allocator = CFGetAllocator(key);
618 *serialized = SecRSAPublicKeyCreatePKCS1(allocator, fullkey);
619
620 if (NULL == *serialized)
621 return errSecDecode;
622 else
623 return errSecSuccess;
624 }
625
626
627 static CFDictionaryRef SecRSAPrivateKeyCopyAttributeDictionary(SecKeyRef key) {
628 CFDictionaryRef dict = NULL;
629 CFDataRef fullKeyBlob = NULL;
630
631 /* PKCS1 encode the key pair. */
632 fullKeyBlob = SecRSAPrivateKeyCopyPKCS1(key);
633 require_quiet(fullKeyBlob, errOut);
634
635 dict = SecKeyGeneratePrivateAttributeDictionary(key, kSecAttrKeyTypeRSA, fullKeyBlob);
636 CFMutableDictionaryRef mutableDict = CFDictionaryCreateMutableCopy(NULL, 0, dict);
637 CFDictionarySetValue(mutableDict, kSecAttrCanDerive, kCFBooleanFalse);
638 CFAssignRetained(dict, mutableDict);
639
640 errOut:
641 CFReleaseSafe(fullKeyBlob);
642
643 return dict;
644 }
645
646 static CFDataRef SecRSAPrivateKeyCopyExternalRepresentation(SecKeyRef key, CFErrorRef *error) {
647 return SecRSAPrivateKeyCopyPKCS1(key);
648 }
649
650 static CFStringRef SecRSAPrivateKeyCopyDescription(SecKeyRef key){
651
652 return CFStringCreateWithFormat(kCFAllocatorDefault,NULL,CFSTR( "<SecKeyRef algorithm id: %lu, key type: %s, version: %d, block size: %zu bits, addr: %p>"), SecKeyGetAlgorithmId(key), key->key_class->name, key->key_class->version, (8*SecKeyGetBlockSize(key)), key);
653
654 }
655
656 SecKeyDescriptor kSecRSAPrivateKeyDescriptor = {
657 .version = kSecKeyDescriptorVersion,
658 .name = "RSAPrivateKey",
659
660 .init = SecRSAPrivateKeyInit,
661 .destroy = SecRSAPrivateKeyDestroy,
662 .blockSize = SecRSAPrivateKeyBlockSize,
663 .copyExternalRepresentation = SecRSAPrivateKeyCopyExternalRepresentation,
664 .copyDictionary = SecRSAPrivateKeyCopyAttributeDictionary,
665 .describe = SecRSAPrivateKeyCopyDescription,
666 .copyPublic = SecRSAPrivateKeyCopyPublicSerialization,
667 .copyOperationResult = SecRSAPrivateKeyCopyOperationResult,
668 };
669
670 /* Private Key API functions. */
671 SecKeyRef SecKeyCreateRSAPrivateKey(CFAllocatorRef allocator,
672 const uint8_t *keyData, CFIndex keyDataLength,
673 SecKeyEncoding encoding) {
674 return SecKeyCreate(allocator, &kSecRSAPrivateKeyDescriptor, keyData,
675 keyDataLength, encoding);
676 }
677
678
679 OSStatus SecRSAKeyGeneratePair(CFDictionaryRef parameters,
680 SecKeyRef *rsaPublicKey, SecKeyRef *rsaPrivateKey) {
681 OSStatus status = errSecParam;
682
683 CFAllocatorRef allocator = NULL; /* @@@ get from parameters. */
684
685 SecKeyRef pubKey = NULL;
686 SecKeyRef privKey = SecKeyCreate(allocator, &kSecRSAPrivateKeyDescriptor,
687 (const void*) parameters, 0, kSecGenerateKey);
688
689 require_quiet(privKey, errOut);
690
691 /* Create SecKeyRef's from the pkcs1 encoded keys. */
692 pubKey = SecKeyCreate(allocator, &kSecRSAPublicKeyDescriptor,
693 privKey->key, 0, kSecExtractPublicFromPrivate);
694
695 require_quiet(pubKey, errOut);
696
697 if (rsaPublicKey) {
698 *rsaPublicKey = pubKey;
699 pubKey = NULL;
700 }
701 if (rsaPrivateKey) {
702 *rsaPrivateKey = privKey;
703 privKey = NULL;
704 }
705
706 status = errSecSuccess;
707
708 errOut:
709 CFReleaseSafe(pubKey);
710 CFReleaseSafe(privKey);
711
712 return status;
713 }