2 * Copyright (c) 2010-2015 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
25 * SecECKey.m - CoreFoundation based ECDSA key object
29 #include "SecECKeyPriv.h"
31 #import <Foundation/Foundation.h>
33 #include <Security/SecKeyInternal.h>
34 #include <Security/SecItem.h>
35 #include <Security/SecBasePriv.h>
36 #include <AssertMacros.h>
37 #include <Security/SecureTransport.h> /* For error codes. */
38 #include <CoreFoundation/CFData.h> /* For error codes. */
39 #include <CoreFoundation/CFNumber.h>
40 #include <Security/SecFramework.h>
41 #include <Security/SecRandom.h>
42 #include <utilities/debugging.h>
43 #include <Security/SecItemPriv.h>
44 #include <Security/SecInternal.h>
45 #include <utilities/SecCFError.h>
46 #include <utilities/SecCFWrappers.h>
47 #include <utilities/array_size.h>
48 #include <corecrypto/ccec.h>
49 #include <corecrypto/ccsha1.h>
50 #include <corecrypto/ccsha2.h>
51 #include <corecrypto/ccrng.h>
52 #include <corecrypto/ccder_decode_eckey.h>
54 #define kMaximumECKeySize 521
56 static CFIndex SecECKeyGetAlgorithmID(SecKeyRef key) {
57 return kSecECDSAAlgorithmID;
67 /* Public key static functions. */
68 static void SecECPublicKeyDestroy(SecKeyRef key) {
69 /* Zero out the public key */
70 ccec_pub_ctx_t pubkey = key->key;
71 if (ccec_ctx_cp(pubkey))
72 cc_clear(ccec_pub_ctx_size(ccn_sizeof_n(ccec_ctx_n(pubkey))), pubkey);
75 static ccec_const_cp_t getCPForPublicSize(CFIndex encoded_length)
77 size_t keysize = ccec_x963_import_pub_size(encoded_length);
78 if(ccec_keysize_is_supported(keysize)) {
79 return ccec_get_cp(keysize);
84 static ccec_const_cp_t getCPForPrivateSize(CFIndex encoded_length)
86 size_t keysize = ccec_x963_import_priv_size(encoded_length);
87 if(ccec_keysize_is_supported(keysize)) {
88 return ccec_get_cp(keysize);
93 static ccoid_t ccoid_secp192r1 = CC_EC_OID_SECP192R1;
94 static ccoid_t ccoid_secp256r1 = CC_EC_OID_SECP256R1;
95 static ccoid_t ccoid_secp224r1 = CC_EC_OID_SECP224R1;
96 static ccoid_t ccoid_secp384r1 = CC_EC_OID_SECP384R1;
97 static ccoid_t ccoid_secp521r1 = CC_EC_OID_SECP521R1;
99 static ccec_const_cp_t ccec_cp_for_oid(const unsigned char *oid)
102 if (ccoid_equal(oid, ccoid_secp192r1)) {
103 return ccec_cp_192();
104 } else if (ccoid_equal(oid, ccoid_secp256r1)) {
105 return ccec_cp_256();
106 } else if (ccoid_equal(oid, ccoid_secp224r1)) {
107 return ccec_cp_224();
108 } else if (ccoid_equal(oid, ccoid_secp384r1)) {
109 return ccec_cp_384();
110 } else if (ccoid_equal(oid, ccoid_secp521r1)) {
111 return ccec_cp_521();
114 return (ccec_const_cp_t){NULL};
117 static OSStatus SecECPublicKeyInit(SecKeyRef key,
118 const uint8_t *keyData, CFIndex keyDataLength, SecKeyEncoding encoding) {
119 ccec_pub_ctx_t pubkey = key->key;
120 OSStatus err = errSecParam;
123 case kSecDERKeyEncoding:
125 const SecDERKey *derKey = (const SecDERKey *)keyData;
126 if (keyDataLength != sizeof(SecDERKey)) {
131 ccec_const_cp_t cp = getCPForPublicSize(derKey->keyLength);
132 require_action_quiet(cp, errOut, err = errSecDecode);
134 /* TODO: Parse and use real params from passed in derKey->algId.params */
135 err = (ccec_import_pub(cp, derKey->keyLength, derKey->key, pubkey)
136 ? errSecDecode : errSecSuccess);
139 case kSecKeyEncodingBytes:
141 ccec_const_cp_t cp = getCPForPublicSize(keyDataLength);
142 require_action_quiet(cp, errOut, err = errSecDecode);
143 err = (ccec_import_pub(cp, keyDataLength, keyData, pubkey)
144 ? errSecDecode : errSecSuccess);
147 case kSecExtractPublicFromPrivate:
149 ccec_full_ctx_t fullKey = (ccec_full_ctx_t)keyData;
151 cc_size fullKeyN = ccec_ctx_n(fullKey);
152 require_quiet(fullKeyN <= ccn_nof(kMaximumECKeySize), errOut);
153 memcpy(pubkey, fullKey, ccec_pub_ctx_size(ccn_sizeof_n(fullKeyN)));
157 case kSecKeyEncodingApplePkcs1:
167 static CFTypeRef SecECPublicKeyCopyOperationResult(SecKeyRef key, SecKeyOperationType operation, SecKeyAlgorithm algorithm,
168 CFArrayRef algorithms, SecKeyOperationMode mode,
169 CFTypeRef in1, CFTypeRef in2, CFErrorRef *error) {
170 if (operation != kSecKeyOperationTypeVerify || !CFEqual(algorithm, kSecKeyAlgorithmECDSASignatureDigestX962)) {
171 // EC public key supports only signature verification with X962 algorithm.
175 if (mode == kSecKeyOperationModePerform) {
178 size_t sigLen = CFDataGetLength(in2);
179 uint8_t *sig = (uint8_t *)CFDataGetBytePtr(in2);
180 ccec_pub_ctx_t pubkey = key->key;
182 err = ccec_verify(pubkey, CFDataGetLength(in1), CFDataGetBytePtr(in1), sigLen, sig, &valid);
184 SecError(errSecVerifyFailed, error, CFSTR("EC signature verification failed (ccerr %d)"), err);
187 SecError(errSecVerifyFailed, error, CFSTR("EC signature verification failed, no match"));
190 return kCFBooleanTrue;
193 // Algorithm is supported.
194 return kCFBooleanTrue;
198 static size_t SecECPublicKeyBlockSize(SecKeyRef key) {
199 /* Get key size in octets */
200 return ccec_ctx_size(ccec_ctx_pub(key->key));
203 /* Encode the public key and return it in a newly allocated CFDataRef. */
204 static CFDataRef SecECPublicKeyExport(CFAllocatorRef allocator,
205 ccec_pub_ctx_t pubkey) {
206 size_t pub_size = ccec_export_pub_size(pubkey);
207 CFMutableDataRef blob = CFDataCreateMutableWithScratch(allocator, pub_size);
208 ccec_export_pub(pubkey, CFDataGetMutableBytePtr(blob));
212 static CFDataRef SecECPublicKeyCopyExternalRepresentation(SecKeyRef key, CFErrorRef *error) {
213 ccec_pub_ctx_t pubkey = key->key;
214 return SecECPublicKeyExport(NULL, pubkey);
217 static OSStatus SecECPublicKeyCopyPublicOctets(SecKeyRef key, CFDataRef *serailziation)
219 ccec_pub_ctx_t pubkey = key->key;
221 CFAllocatorRef allocator = CFGetAllocator(key);
222 *serailziation = SecECPublicKeyExport(allocator, pubkey);
224 if (NULL == *serailziation)
227 return errSecSuccess;
230 static CFDictionaryRef SecECPublicKeyCopyAttributeDictionary(SecKeyRef key) {
231 CFDictionaryRef dict = SecKeyGeneratePublicAttributeDictionary(key, kSecAttrKeyTypeEC);
232 CFMutableDictionaryRef mutableDict = CFDictionaryCreateMutableCopy(NULL, 0, dict);
233 CFDictionarySetValue(mutableDict, kSecAttrCanDerive, kCFBooleanFalse);
234 CFAssignRetained(dict, mutableDict);
239 getCurveName(SecKeyRef key)
241 SecECNamedCurve curveType = SecECKeyGetNamedCurve(key);
245 case kSecECCurveSecp256r1:
246 return "kSecECCurveSecp256r1";
248 case kSecECCurveSecp384r1:
249 return "kSecECCurveSecp384r1";
251 case kSecECCurveSecp521r1:
252 return "kSecECCurveSecp521r1";
254 return "kSecECCurveNone";
258 static CFStringRef SecECPublicKeyCopyKeyDescription(SecKeyRef key)
260 NSMutableString *strings[2];
261 const char* curve = getCurveName(key);
263 ccec_pub_ctx_t ecPubkey = key->key;
264 size_t len = ccec_ctx_size(ecPubkey);
265 NSMutableData *buffer = [NSMutableData dataWithLength:len];
266 for (int i = 0; i < 2; ++i) {
267 ccn_write_uint(ccec_ctx_n(ecPubkey), (i == 0) ? ccec_ctx_x(ecPubkey) : ccec_ctx_y(ecPubkey), len, buffer.mutableBytes);
268 strings[i] = [NSMutableString stringWithCapacity:len * 2];
269 for (size_t byteIndex = 0; byteIndex < len; ++byteIndex) {
270 [strings[i] appendFormat:@"%02X", ((const uint8_t *)buffer.bytes)[byteIndex]];
274 NSString *description = [NSString stringWithFormat:@"<SecKeyRef curve type: %s, algorithm id: %lu, key type: %s, version: %d, block size: %zu bits, y: %@, x: %@, addr: %p>",
275 curve, (long)SecKeyGetAlgorithmId(key), key->key_class->name, key->key_class->version,
276 8 * SecKeyGetBlockSize(key), strings[1], strings[0], key];
277 return CFBridgingRetain(description);
280 static const struct ccec_rfc6637_curve * get_rfc6637_curve(SecKeyRef key)
282 SecECNamedCurve curveType = SecECKeyGetNamedCurve(key);
284 if (curveType == kSecECCurveSecp256r1) {
285 return &ccec_rfc6637_dh_curve_p256;
286 } else if (curveType == kSecECCurveSecp521r1) {
287 return &ccec_rfc6637_dh_curve_p521;
292 static CFDataRef SecECKeyCopyWrapKey(SecKeyRef key, SecKeyWrapType type, CFDataRef unwrappedKey, CFDictionaryRef parameters, CFDictionaryRef *outParam, CFErrorRef *error)
294 ccec_pub_ctx_t pubkey = key->key;
295 int err = errSecUnimplemented;
296 const struct ccec_rfc6637_curve *curve;
297 const struct ccec_rfc6637_wrap *wrap = NULL;
301 if (type != kSecKeyWrapPublicKeyPGP) {
302 SecError(errSecUnsupportedOperation, error, CFSTR("unsupported key wrapping algorithm"));
306 curve = get_rfc6637_curve(key);
308 SecError(errSecUnsupportedOperation, error, CFSTR("unsupported curve"));
312 CFNumberRef num = CFDictionaryGetValue(parameters, _kSecKeyWrapPGPSymAlg);
313 if (!isNumber(num) || !CFNumberGetValue(num, kCFNumberSInt8Type, &sym_alg)) {
314 SecError(errSecUnsupportedOperation, error, CFSTR("unknown symalg given"));
318 CFDataRef fingerprint = CFDictionaryGetValue(parameters, _kSecKeyWrapPGPFingerprint);
319 if (!isData(fingerprint) || CFDataGetLength(fingerprint) < kSecKeyWrapPGPFingerprintMinSize) {
320 SecError(errSecUnsupportedOperation, error, CFSTR("invalid fingerprint"));
324 CFTypeRef wrapAlg = CFDictionaryGetValue(parameters, _kSecKeyWrapPGPWrapAlg);
325 if (wrapAlg == NULL) {
326 SecError(errSecUnsupportedOperation, error, CFSTR("no wrap alg"));
328 } else if (CFEqual(wrapAlg, _kSecKeyWrapRFC6637WrapDigestSHA256KekAES128)) {
329 wrap = &ccec_rfc6637_wrap_sha256_kek_aes128;
330 } else if (CFEqual(wrapAlg, _kSecKeyWrapRFC6637WrapDigestSHA512KekAES256)) {
331 wrap = &ccec_rfc6637_wrap_sha512_kek_aes256;
333 SecError(errSecUnsupportedOperation, error, CFSTR("unknown wrap alg"));
337 num = CFDictionaryGetValue(parameters, _kSecKeyWrapRFC6637Flags);
339 if (!CFNumberGetValue(num, kCFNumberSInt32Type, &flags)) {
340 SecError(errSecUnsupportedOperation, error, CFSTR("invalid flags: %@"), num);
344 SecError(errSecUnsupportedOperation, error, CFSTR("unknown flags"));
348 CFIndex unwrappedKey_size = CFDataGetLength(unwrappedKey);
350 CFIndex output_size = ccec_rfc6637_wrap_key_size(pubkey, flags, unwrappedKey_size);
351 if (output_size == 0) {
352 SecError(errSecUnsupportedOperation, error, CFSTR("can't wrap that key, can't build size"));
356 CFMutableDataRef data = CFDataCreateMutableWithScratch(NULL, output_size);
357 require_quiet(data, errOut);
359 err = ccec_rfc6637_wrap_key(pubkey, CFDataGetMutableBytePtr(data), flags,
360 sym_alg, CFDataGetLength(unwrappedKey), CFDataGetBytePtr(unwrappedKey),
361 curve, wrap, CFDataGetBytePtr(fingerprint),
364 SecError(errSecUnsupportedOperation, error, CFSTR("Failed to wrap key"));
372 SecKeyDescriptor kSecECPublicKeyDescriptor = {
373 .version = kSecKeyDescriptorVersion,
374 .name = "ECPublicKey",
375 .extraBytes = ccec_pub_ctx_size(ccn_sizeof(kMaximumECKeySize)),
376 .init = SecECPublicKeyInit,
377 .destroy = SecECPublicKeyDestroy,
378 .blockSize = SecECPublicKeyBlockSize,
379 .copyDictionary = SecECPublicKeyCopyAttributeDictionary,
380 .copyExternalRepresentation = SecECPublicKeyCopyExternalRepresentation,
381 .describe = SecECPublicKeyCopyKeyDescription,
382 .getAlgorithmID = SecECKeyGetAlgorithmID,
383 .copyPublic = SecECPublicKeyCopyPublicOctets,
384 .copyWrapKey = SecECKeyCopyWrapKey,
385 .copyOperationResult = SecECPublicKeyCopyOperationResult,
388 /* Public Key API functions. */
389 SecKeyRef SecKeyCreateECPublicKey(CFAllocatorRef allocator,
390 const uint8_t *keyData, CFIndex keyDataLength,
391 SecKeyEncoding encoding) {
392 return SecKeyCreate(allocator, &kSecECPublicKeyDescriptor, keyData,
393 keyDataLength, encoding);
404 /* Private key static functions. */
405 static void SecECPrivateKeyDestroy(SecKeyRef key) {
406 /* Zero out the public key */
407 ccec_full_ctx_t fullkey = key->key;
409 if (ccec_ctx_cp(fullkey))
410 cc_clear(ccec_full_ctx_size(ccn_sizeof_n(ccec_ctx_n(fullkey))), fullkey);
414 static OSStatus SecECPrivateKeyInit(SecKeyRef key,
415 const uint8_t *keyData, CFIndex keyDataLength, SecKeyEncoding encoding) {
416 ccec_full_ctx_t fullkey = key->key;
417 OSStatus err = errSecParam;
420 case kSecKeyEncodingPkcs1:
422 /* TODO: DER import size (and thus cp), pub.x, pub.y and k. */
423 //err = ecc_import(keyData, keyDataLength, fullkey);
425 /* DER != PKCS#1, but we'll go along with it */
426 const unsigned char *oid;
430 require_noerr_quiet(ccec_der_import_priv_keytype(keyDataLength, keyData, (ccoid_t*)&oid, &n), abort);
431 cp = ccec_cp_for_oid(oid);
433 cp = ccec_curve_for_length_lookup(n * 8 /* bytes -> bits */,
434 ccec_cp_192(), ccec_cp_224(), ccec_cp_256(), ccec_cp_384(), ccec_cp_521(), NULL);
436 require_action_quiet(cp != NULL, abort, err = errSecDecode);
437 ccec_ctx_init(cp, fullkey);
439 require_noerr_quiet(ccec_der_import_priv(cp, keyDataLength, keyData, fullkey), abort);
443 case kSecKeyEncodingBytes:
445 ccec_const_cp_t cp = getCPForPrivateSize(keyDataLength);
446 require_quiet(cp != NULL, abort);
448 ccec_ctx_init(cp, fullkey);
449 size_t pubSize = ccec_export_pub_size(ccec_ctx_pub(fullkey));
451 require_quiet(pubSize < (size_t) keyDataLength, abort);
452 require_noerr_action_quiet(ccec_import_pub(cp, pubSize, keyData, ccec_ctx_pub(fullkey)),
458 keyDataLength -= pubSize;
460 cc_unit *k = ccec_ctx_k(fullkey);
461 require_noerr_action_quiet(ccn_read_uint(ccec_ctx_n(fullkey), k, keyDataLength, keyData),
469 case kSecGenerateKey:
471 CFDictionaryRef parameters = (CFDictionaryRef) keyData;
473 CFTypeRef ksize = CFDictionaryGetValue(parameters, kSecAttrKeySizeInBits);
474 CFIndex keyLengthInBits = getIntValue(ksize);
476 ccec_const_cp_t cp = ccec_get_cp(keyLengthInBits);
479 secwarning("Invalid or missing key size in: %@", parameters);
480 return errSecKeySizeNotAllowed;
483 if (!ccec_generate_key_fips(cp, ccrng_seckey, fullkey))
495 static CFTypeRef SecECPrivateKeyCopyOperationResult(SecKeyRef key, SecKeyOperationType operation, SecKeyAlgorithm algorithm,
496 CFArrayRef allAlgorithms, SecKeyOperationMode mode,
497 CFTypeRef in1, CFTypeRef in2, CFErrorRef *error) {
498 // Default answer is 'unsupported', unless we find out that we can support it.
499 CFTypeRef result = kCFNull;
501 ccec_full_ctx_t fullkey = key->key;
503 case kSecKeyOperationTypeSign: {
504 if (CFEqual(algorithm, kSecKeyAlgorithmECDSASignatureDigestX962)) {
505 if (mode == kSecKeyOperationModePerform) {
506 // Perform x962 mode of signature.
507 size_t size = ccec_sign_max_size(ccec_ctx_cp(fullkey));
508 result = CFDataCreateMutableWithScratch(NULL, size);
509 int err = ccec_sign(fullkey, CFDataGetLength(in1), CFDataGetBytePtr(in1),
510 &size, CFDataGetMutableBytePtr((CFMutableDataRef)result), ccrng_seckey);
511 require_action_quiet(err == 0, out, (CFReleaseNull(result),
512 SecError(errSecParam, error, CFSTR("%@: X962 signing failed (ccerr %d)"),
514 CFDataSetLength((CFMutableDataRef)result, size);
516 // Operation is supported.
517 result = kCFBooleanTrue;
522 case kSecKeyOperationTypeKeyExchange:
523 if (CFEqual(algorithm, kSecKeyAlgorithmECDHKeyExchangeStandard) ||
524 CFEqual(algorithm, kSecKeyAlgorithmECDHKeyExchangeCofactor)) {
525 if (mode == kSecKeyOperationModePerform) {
527 ccec_const_cp_t cp = getCPForPublicSize(CFDataGetLength(in1));
528 require_action_quiet(cp != NULL, out,
529 SecError(errSecParam, error, CFSTR("ECpriv sharedsecret: bad public key")));
530 ccec_pub_ctx_decl_cp(cp, pubkey);
531 err = ccec_import_pub(cp, CFDataGetLength(in1), CFDataGetBytePtr(in1), pubkey);
532 require_noerr_action_quiet(err, out, SecError(errSecParam, error,
533 CFSTR("ECpriv sharedsecret: bad public key (err %d)"), err));
534 size_t size = ccec_ccn_size(cp);
535 result = CFDataCreateMutableWithScratch(NULL, size);
536 err = ccecdh_compute_shared_secret(fullkey, pubkey, &size,
537 CFDataGetMutableBytePtr((CFMutableDataRef)result), ccrng_seckey);
538 require_noerr_action_quiet(err, out, (CFReleaseNull(result),
539 SecError(errSecDecode, error,
540 CFSTR("ECpriv failed to compute shared secret (err %d)"), err)));
541 CFDataSetLength((CFMutableDataRef)result, size);
543 // Operation is supported.
544 result = kCFBooleanTrue;
556 static size_t SecECPrivateKeyBlockSize(SecKeyRef key) {
557 ccec_full_ctx_t fullkey = key->key;
558 /* Get key size in octets */
559 return ccec_ctx_size(fullkey);
562 static OSStatus SecECPrivateKeyCopyPublicOctets(SecKeyRef key, CFDataRef *serailziation)
564 ccec_full_ctx_t fullkey = key->key;
566 CFAllocatorRef allocator = CFGetAllocator(key);
567 *serailziation = SecECPublicKeyExport(allocator, ccec_ctx_pub(fullkey));
569 if (NULL == *serailziation)
572 return errSecSuccess;
575 static CFDataRef SecECPrivateKeyCopyExternalRepresentation(SecKeyRef key, CFErrorRef *error) {
576 ccec_full_ctx_t fullkey = key->key;
577 size_t prime_size = ccec_cp_prime_size(ccec_ctx_cp(fullkey));
578 size_t key_size = ccec_export_pub_size(ccec_ctx_pub(fullkey)) + prime_size;
579 CFMutableDataRef blob = CFDataCreateMutableWithScratch(NULL, key_size);
580 ccec_export_pub(ccec_ctx_pub(fullkey), CFDataGetMutableBytePtr(blob));
581 UInt8 *dest = CFDataGetMutableBytePtr(blob) + ccec_export_pub_size(ccec_ctx_pub(fullkey));
582 const cc_unit *k = ccec_ctx_k(fullkey);
583 ccn_write_uint_padded(ccec_ctx_n(fullkey), k, prime_size, dest);
587 static CFDictionaryRef SecECPrivateKeyCopyAttributeDictionary(SecKeyRef key) {
588 /* Export the full ec key pair. */
589 CFDataRef fullKeyBlob = SecECPrivateKeyCopyExternalRepresentation(key, NULL);
591 CFDictionaryRef dict = SecKeyGeneratePrivateAttributeDictionary(key, kSecAttrKeyTypeEC, fullKeyBlob);
592 CFReleaseSafe(fullKeyBlob);
595 static CFStringRef SecECPrivateKeyCopyKeyDescription(SecKeyRef key) {
597 const char* curve = getCurveName(key);
599 return CFStringCreateWithFormat(kCFAllocatorDefault,NULL,CFSTR( "<SecKeyRef curve type: %s, algorithm id: %lu, key type: %s, version: %d, block size: %zu bits, addr: %p>"), curve, (long)SecKeyGetAlgorithmId(key), key->key_class->name, key->key_class->version, (8*SecKeyGetBlockSize(key)), key);
603 static CFDataRef SecECKeyCopyUnwrapKey(SecKeyRef key, SecKeyWrapType type, CFDataRef wrappedKey, CFDictionaryRef parameters, CFDictionaryRef *outParam, CFErrorRef *error)
605 const struct ccec_rfc6637_curve *curve;
606 const struct ccec_rfc6637_unwrap *unwrap;
607 ccec_full_ctx_t fullkey = key->key;
608 CFMutableDataRef data;
613 curve = get_rfc6637_curve(key);
615 SecError(errSecUnsupportedOperation, error, CFSTR("unsupported curve"));
619 CFTypeRef wrapAlg = CFDictionaryGetValue(parameters, _kSecKeyWrapPGPWrapAlg);
620 if (wrapAlg == NULL) {
621 SecError(errSecUnsupportedOperation, error, CFSTR("no wrap alg"));
623 } else if (CFEqual(wrapAlg, _kSecKeyWrapRFC6637WrapDigestSHA256KekAES128)) {
624 unwrap = &ccec_rfc6637_unwrap_sha256_kek_aes128;
625 } else if (CFEqual(wrapAlg, _kSecKeyWrapRFC6637WrapDigestSHA512KekAES256)) {
626 unwrap = &ccec_rfc6637_unwrap_sha512_kek_aes256;
628 SecError(errSecUnsupportedOperation, error, CFSTR("unknown wrap alg"));
632 CFDataRef fingerprint = CFDictionaryGetValue(parameters, _kSecKeyWrapPGPFingerprint);
633 if (!isData(fingerprint) || CFDataGetLength(fingerprint) < kSecKeyWrapPGPFingerprintMinSize) {
634 SecError(errSecUnsupportedOperation, error, CFSTR("invalid fingerprint"));
638 CFNumberRef num = CFDictionaryGetValue(parameters, _kSecKeyWrapRFC6637Flags);
640 if (!CFNumberGetValue(num, kCFNumberSInt32Type, &flags)) {
641 SecError(errSecUnsupportedOperation, error, CFSTR("invalid flags: %@"), num);
645 SecError(errSecUnsupportedOperation, error, CFSTR("unknown flags"));
649 size_t keysize = CFDataGetLength(wrappedKey);
650 data = CFDataCreateMutableWithScratch(NULL, keysize);
654 res = ccec_rfc6637_unwrap_key(fullkey, &keysize, CFDataGetMutableBytePtr(data),
655 flags, &sym_alg, curve, unwrap,
656 CFDataGetBytePtr(fingerprint),
657 CFDataGetLength(wrappedKey), CFDataGetBytePtr(wrappedKey));
660 SecError(errSecUnsupportedOperation, error, CFSTR("failed to wrap key"));
663 assert(keysize <= (size_t)CFDataGetLength(data));
664 CFDataSetLength(data, keysize);
667 CFMutableDictionaryRef out = CFDictionaryCreateMutableForCFTypes(NULL);
669 CFNumberRef num = CFNumberCreate(NULL, kCFNumberSInt8Type, &sym_alg);
671 CFDictionarySetValue(out, _kSecKeyWrapPGPSymAlg, num);
681 SecKeyDescriptor kSecECPrivateKeyDescriptor = {
682 .version = kSecKeyDescriptorVersion,
683 .name = "ECPrivateKey",
684 .extraBytes = ccec_full_ctx_size(ccn_sizeof(kMaximumECKeySize)),
686 .init = SecECPrivateKeyInit,
687 .destroy = SecECPrivateKeyDestroy,
688 .blockSize = SecECPrivateKeyBlockSize,
689 .copyDictionary = SecECPrivateKeyCopyAttributeDictionary,
690 .describe = SecECPrivateKeyCopyKeyDescription,
691 .getAlgorithmID = SecECKeyGetAlgorithmID,
692 .copyPublic = SecECPrivateKeyCopyPublicOctets,
693 .copyExternalRepresentation = SecECPrivateKeyCopyExternalRepresentation,
694 .copyWrapKey = SecECKeyCopyWrapKey,
695 .copyUnwrapKey = SecECKeyCopyUnwrapKey,
696 .copyOperationResult = SecECPrivateKeyCopyOperationResult,
699 /* Private Key API functions. */
700 SecKeyRef SecKeyCreateECPrivateKey(CFAllocatorRef allocator,
701 const uint8_t *keyData, CFIndex keyDataLength,
702 SecKeyEncoding encoding) {
703 return SecKeyCreate(allocator, &kSecECPrivateKeyDescriptor, keyData,
704 keyDataLength, encoding);
708 OSStatus SecECKeyGeneratePair(CFDictionaryRef parameters,
709 SecKeyRef *publicKey, SecKeyRef *privateKey) {
710 OSStatus status = errSecParam;
712 CFAllocatorRef allocator = NULL; /* @@@ get from parameters. */
713 SecKeyRef pubKey = NULL;
715 SecKeyRef privKey = SecKeyCreate(allocator, &kSecECPrivateKeyDescriptor,
716 (const void*) parameters, 0, kSecGenerateKey);
718 require_quiet(privKey, errOut);
720 /* Create SecKeyRef's from the pkcs1 encoded keys. */
721 pubKey = SecKeyCreate(allocator, &kSecECPublicKeyDescriptor,
722 privKey->key, 0, kSecExtractPublicFromPrivate);
724 require_quiet(pubKey, errOut);
731 *privateKey = privKey;
735 status = errSecSuccess;
738 CFReleaseSafe(pubKey);
739 CFReleaseSafe(privKey);
745 /* It's debatable whether this belongs here or in the ssl code since the
746 curve values come from a tls related rfc4492. */
747 SecECNamedCurve SecECKeyGetNamedCurve(SecKeyRef key) {
748 SecECNamedCurve result = kSecECCurveNone;
749 CFDictionaryRef attributes = NULL;
750 require_quiet(SecKeyGetAlgorithmId(key) == kSecECDSAAlgorithmID, out);
751 require_quiet(attributes = SecKeyCopyAttributes(key), out);
752 CFTypeRef bitsRef = CFDictionaryGetValue(attributes, kSecAttrKeySizeInBits);
754 require_quiet(bitsRef != NULL && CFGetTypeID(bitsRef) == CFNumberGetTypeID() &&
755 CFNumberGetValue(bitsRef, kCFNumberCFIndexType, &bits), out);
759 result = kSecECCurveSecp192r1;
762 result = kSecECCurveSecp224r1;
766 result = kSecECCurveSecp256r1;
769 result = kSecECCurveSecp384r1;
772 result = kSecECCurveSecp521r1;
777 CFReleaseSafe(attributes);
781 CFDataRef SecECKeyCopyPublicBits(SecKeyRef key) {
782 CFDataRef bytes = NULL;
783 SecKeyCopyPublicBytes(key, &bytes);
787 /* Vile accessors that get us the pub or priv key to use temporarily */
789 bool SecECDoWithFullKey(SecKeyRef key, CFErrorRef* error, void (^action)(ccec_full_ctx_t private)) {
790 if (key->key_class == &kSecECPrivateKeyDescriptor) {
793 return SecError(errSecParam, error, CFSTR("Not an EC Full Key object, sorry can't do."));
799 bool SecECDoWithPubKey(SecKeyRef key, CFErrorRef* error, void (^action)(ccec_pub_ctx_t public)) {
800 if (key->key_class == &kSecECPublicKeyDescriptor) {
803 return SecError(errSecParam, error, CFSTR("Not an EC Public Key object, sorry can't do."));