]> git.saurik.com Git - apple/security.git/blob - keychain/SecKeyPriv.h
Security-58286.51.6.tar.gz
[apple/security.git] / keychain / SecKeyPriv.h
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 @header SecKeyPriv
26 The functions provided in SecKeyPriv.h implement and manage a particular
27 type of keychain item that represents a key. A key can be stored in a
28 keychain, but a key can also be a transient object.
29
30 You can use a key as a keychain item in most functions.
31 */
32
33 #ifndef _SECURITY_SECKEYPRIV_H_
34 #define _SECURITY_SECKEYPRIV_H_
35
36 #include <Security/SecBase.h>
37 #include <Security/SecKey.h>
38 #include <Security/SecAsn1Types.h>
39 #include <CoreFoundation/CFRuntime.h>
40
41 #if SEC_OS_OSX
42 #include <Security/SecKey.h>
43 #include <Security/x509defs.h>
44 #include <AvailabilityMacros.h>
45 #endif
46
47 __BEGIN_DECLS
48
49 #if SEC_OS_IPHONE
50 typedef struct __SecDERKey {
51 uint8_t *oid;
52 CFIndex oidLength;
53
54 uint8_t *parameters;
55 CFIndex parametersLength;
56
57 /* Contents of BIT STRING in DER Encoding */
58 uint8_t *key;
59 CFIndex keyLength;
60 } SecDERKey;
61 #endif // SEC_OS_IPHONE
62
63 typedef struct SecRSAPublicKeyParams {
64 uint8_t *modulus; /* modulus */
65 CFIndex modulusLength;
66 uint8_t *exponent; /* public exponent */
67 CFIndex exponentLength;
68 } SecRSAPublicKeyParams;
69
70 typedef uint32_t SecKeyEncoding;
71 enum {
72 /* Typically only used for symmetric keys. */
73 kSecKeyEncodingRaw = 0,
74
75 /* RSA keys are DER-encoded according to PKCS1. */
76 kSecKeyEncodingPkcs1 = 1,
77
78 /* RSA keys are DER-encoded according to PKCS1 with Apple Extensions. */
79 kSecKeyEncodingApplePkcs1 = 2,
80
81 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
82 to a SecRSAPublicKeyParams and keyDataLength is
83 sizeof(SecRSAPublicKeyParams). */
84 kSecKeyEncodingRSAPublicParams = 3,
85
86 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
87 to a SecRSAPublicKeyParams and keyDataLength is
88 sizeof(SecRSAPublicKeyParams). */
89 kSecDERKeyEncoding = 4,
90
91 /* Internal "encodings to send other data" */
92 kSecGenerateKey = 5,
93 kSecExtractPublicFromPrivate = 6,
94
95 /* Encoding came from SecKeyCopyPublicBytes for a public key,
96 or internally from a private key */
97 kSecKeyEncodingBytes = 7,
98
99 /* Handing in a private key from corecrypto directly. */
100 kSecKeyCoreCrypto = 8,
101
102 };
103
104 typedef uint32_t SecKeyWrapType;
105 enum {
106 /* wrap key in RFC3394 (AESWrap) */
107 kSecKeyWrapRFC3394 = 0,
108
109 /* wrap key in PGP style (support EC keys only right now) */
110 kSecKeyWrapPublicKeyPGP = 1,
111
112 };
113
114 typedef CF_ENUM(CFIndex, SecKeyOperationMode) {
115 kSecKeyOperationModePerform = 0,
116 kSecKeyOperationModeCheckIfSupported = 1,
117 };
118
119 typedef OSStatus (*SecKeyInitMethod)(SecKeyRef, const uint8_t *, CFIndex,
120 SecKeyEncoding);
121 typedef void (*SecKeyDestroyMethod)(SecKeyRef);
122 typedef OSStatus (*SecKeyRawSignMethod)(SecKeyRef key, SecPadding padding,
123 const uint8_t *dataToSign, size_t dataToSignLen,
124 uint8_t *sig, size_t *sigLen);
125 typedef OSStatus (*SecKeyRawVerifyMethod)(
126 SecKeyRef key, SecPadding padding, const uint8_t *signedData,
127 size_t signedDataLen, const uint8_t *sig, size_t sigLen);
128 typedef OSStatus (*SecKeyEncryptMethod)(SecKeyRef key, SecPadding padding,
129 const uint8_t *plainText, size_t plainTextLen,
130 uint8_t *cipherText, size_t *cipherTextLen);
131 typedef OSStatus (*SecKeyDecryptMethod)(SecKeyRef key, SecPadding padding,
132 const uint8_t *cipherText, size_t cipherTextLen,
133 uint8_t *plainText, size_t *plainTextLen);
134 typedef OSStatus (*SecKeyComputeMethod)(SecKeyRef key,
135 const uint8_t *pub_key, size_t pub_key_len,
136 uint8_t *computed_key, size_t *computed_key_len);
137 typedef size_t (*SecKeyBlockSizeMethod)(SecKeyRef key);
138 typedef CFDictionaryRef (*SecKeyCopyDictionaryMethod)(SecKeyRef key);
139 typedef CFIndex (*SecKeyGetAlgorithmIDMethod)(SecKeyRef key);
140 typedef OSStatus (*SecKeyCopyPublicBytesMethod)(SecKeyRef key, CFDataRef *serialization);
141 typedef CFDataRef (*SecKeyCopyWrapKeyMethod)(SecKeyRef key, SecKeyWrapType type, CFDataRef unwrappedKey, CFDictionaryRef parameters, CFDictionaryRef *outParam, CFErrorRef *error);
142 typedef CFDataRef (*SecKeyCopyUnwrapKeyMethod)(SecKeyRef key, SecKeyWrapType type, CFDataRef wrappedKey, CFDictionaryRef parameters, CFDictionaryRef *outParam, CFErrorRef *error);
143 typedef CFStringRef (*SecKeyDescribeMethod)(SecKeyRef key);
144
145 typedef CFDataRef (*SecKeyCopyExternalRepresentationMethod)(SecKeyRef key, CFErrorRef *error);
146 typedef SecKeyRef (*SecKeyCopyPublicKeyMethod)(SecKeyRef key);
147 typedef Boolean (*SecKeyIsEqualMethod)(SecKeyRef key1, SecKeyRef key2);
148 typedef SecKeyRef (*SecKeyCreateDuplicateMethod)(SecKeyRef key);
149 typedef Boolean (*SecKeySetParameterMethod)(SecKeyRef key, CFStringRef name, CFPropertyListRef value, CFErrorRef *error);
150
151 /*!
152 @abstract Performs cryptographic operation with the key.
153 @param key Key to perform the operation on.
154 @param operation Type of operation to be performed.
155 @param algorithm Algorithm identifier for the operation. Determines format of input and output data.
156 @param allAlgorithms Array of algorithms which were traversed until we got to this operation. The last member of this array is always the same as @c algorithm parameter.
157 @param mode Mode in which the operation is performed. Two available modes are checking only if the operation can be performed or actually performing the operation.
158 @param in1 First input parameter for the operation, meaningful only in ModePerform.
159 @param in2 Second input parameter for the operation, meaningful only in ModePerform.
160 @param error Error details when NULL is returned.
161 @return NULL if some failure occured. kCFNull if operation/algorithm/key combination is not supported, otherwise the result of the operation or kCFBooleanTrue in ModeCheckIfSupported.
162 */
163 typedef CFTypeRef(*SecKeyCopyOperationResultMethod)(SecKeyRef key, SecKeyOperationType operation, SecKeyAlgorithm algorithm, CFArrayRef allAlgorithms, SecKeyOperationMode mode, CFTypeRef in1, CFTypeRef in2, CFErrorRef *error);
164
165 #define kSecKeyDescriptorVersion (4)
166
167 typedef struct __SecKeyDescriptor {
168 /* Version of this SecKeyDescriptor. Must be kSecKeyDescriptorVersion. */
169 uint32_t version;
170
171 /* Name of this key class for use by SecKeyShow(). */
172 const char *name;
173
174 /* If nonzero, SecKeyCreate will allocate this many bytes for the key
175 field in the SecKeyRef it creates. If zero key is NULL and the
176 implementor can choose to dynamically allocate it in the init
177 function and free it in the destroy function. */
178 uint32_t extraBytes;
179
180 /* Called by SecKeyCreate(). */
181 SecKeyInitMethod init;
182 /* Called by destructor (final CFRelease() or gc if using). */
183 SecKeyDestroyMethod destroy;
184 /* Called by SecKeyRawSign(). */
185 SecKeyRawSignMethod rawSign;
186 /* Called by SecKeyRawVerify(). */
187 SecKeyRawVerifyMethod rawVerify;
188 /* Called by SecKeyEncrypt(). */
189 SecKeyEncryptMethod encrypt;
190 /* Called by SecKeyDecrypt(). */
191 SecKeyDecryptMethod decrypt;
192 /* Reserved for future use. */
193 SecKeyComputeMethod compute;
194 /* Called by SecKeyGetBlockSize(). */
195 SecKeyBlockSizeMethod blockSize;
196 /* Called by SecKeyCopyAttributeDictionary(), which is private. */
197 SecKeyCopyDictionaryMethod copyDictionary;
198 /* Called by SecKeyDescribeMethod(). */
199 SecKeyDescribeMethod describe;
200 #if kSecKeyDescriptorVersion > 0
201 /* Called by SecKeyCopyAttributeDictionary(), which is private. */
202 SecKeyGetAlgorithmIDMethod getAlgorithmID;
203 #endif
204 #if kSecKeyDescriptorVersion > 1
205 SecKeyCopyPublicBytesMethod copyPublic;
206 #endif
207 #if kSecKeyDescriptorVersion > 2
208 SecKeyCopyWrapKeyMethod copyWrapKey;
209 SecKeyCopyUnwrapKeyMethod copyUnwrapKey;
210 #endif
211 #if kSecKeyDescriptorVersion > 3
212 SecKeyCopyExternalRepresentationMethod copyExternalRepresentation;
213 SecKeyCopyPublicKeyMethod copyPublicKey;
214 SecKeyCopyOperationResultMethod copyOperationResult;
215 SecKeyIsEqualMethod isEqual;
216 SecKeyCreateDuplicateMethod createDuplicate;
217 SecKeySetParameterMethod setParameter;
218 #endif
219 } SecKeyDescriptor;
220
221 #if SEC_OS_IPHONE
222 struct __SecKey {
223 CFRuntimeBase _base;
224
225 const SecKeyDescriptor *key_class;
226
227 #if !TARGET_OS_IPHONE
228 // On OSX, keep optional SecKeyRef which holds dynamically, on-demand created CSSM-based key with the same
229 // key material. It is used to implement SecKeyGetCSSMKey().
230 SecKeyRef cdsaKey;
231 #endif
232
233 /* The actual key handled by class. */
234 void *key;
235 };
236 #endif
237
238 /* Create a public key from a CFData containing a SubjectPublicKeyInfo in DER format. */
239 SecKeyRef SecKeyCreateFromSubjectPublicKeyInfoData(CFAllocatorRef allocator,
240 CFDataRef subjectPublicKeyInfoData);
241
242 /* Crete a SubjectPublicKeyInfo in DER format from a SecKey */
243 CFDataRef SecKeyCopySubjectPublicKeyInfo(SecKeyRef key);
244
245
246 #if SEC_OS_IPHONE
247 /*!
248 @function SecKeyCreate
249 @abstract Given a private key and data to sign, generate a digital signature.
250 @param allocator allocator to use when allocating this key instance.
251 @param key_class pointer to a SecKeyDescriptor.
252 @param keyData The second argument to the init() function in the key_class.
253 @param keyDataLength The third argument to the init() function in the key_class.
254 @param encoding The fourth argument to the init() function in the key_class.
255 @result A newly allocated SecKeyRef.
256 */
257 SecKeyRef SecKeyCreate(CFAllocatorRef allocator,
258 const SecKeyDescriptor *key_class, const uint8_t *keyData,
259 CFIndex keyDataLength, SecKeyEncoding encoding);
260
261 /* Create a public key from an oid, params and keyData all in DER format. */
262 SecKeyRef SecKeyCreatePublicFromDER(CFAllocatorRef allocator,
263 const SecAsn1Oid *oid1, const SecAsn1Item *params,
264 const SecAsn1Item *keyData);
265
266 /* Create public key from private key */
267 SecKeyRef SecKeyCreatePublicFromPrivate(SecKeyRef privateKey);
268 #endif // SEC_OS_IPHONE
269
270 /* Get Private Key (if present) by publicKey. */
271 SecKeyRef SecKeyCopyMatchingPrivateKey(SecKeyRef publicKey, CFErrorRef *error);
272
273 OSStatus SecKeyGetMatchingPrivateKeyStatus(SecKeyRef publicKey, CFErrorRef *error);
274 CFDataRef SecKeyCreatePersistentRefToMatchingPrivateKey(SecKeyRef publicKey, CFErrorRef *error);
275
276 /* Return an attribute dictionary used to find a private key by public key hash */
277 CFDictionaryRef CreatePrivateKeyMatchingQuery(SecKeyRef publicKey, bool returnPersistentRef);
278
279 /* Return a key from an attribute dictionary that was used to store this item
280 in a keychain. */
281 SecKeyRef SecKeyCreateFromAttributeDictionary(CFDictionaryRef refAttributes);
282
283 OSStatus SecKeyDigestAndVerify(
284 SecKeyRef key, /* Public key */
285 const SecAsn1AlgId *algId, /* algorithm oid/params */
286 const uint8_t *dataToDigest, /* signature over this data */
287 size_t dataToDigestLen,/* length of dataToDigest */
288 const uint8_t *sig, /* signature to verify */
289 size_t sigLen); /* length of sig */
290
291 #if SEC_OS_IPHONE
292 /* Return an attribute dictionary used to store this item in a keychain. */
293 CFDictionaryRef SecKeyCopyAttributeDictionary(SecKeyRef key);
294
295 OSStatus SecKeyDigestAndSign(
296 SecKeyRef key, /* Private key */
297 const SecAsn1AlgId *algId, /* algorithm oid/params */
298 const uint8_t *dataToDigest, /* signature over this data */
299 size_t dataToDigestLen,/* length of dataToDigest */
300 uint8_t *sig, /* signature, RETURNED */
301 size_t *sigLen); /* IN/OUT */
302
303 OSStatus SecKeyVerifyDigest(
304 SecKeyRef key, /* Private key */
305 const SecAsn1AlgId *algId, /* algorithm oid/params */
306 const uint8_t *digestData, /* signature over this digest */
307 size_t digestDataLen,/* length of dataToDigest */
308 const uint8_t *sig, /* signature to verify */
309 size_t sigLen); /* length of sig */
310
311 OSStatus SecKeySignDigest(
312 SecKeyRef key, /* Private key */
313 const SecAsn1AlgId *algId, /* algorithm oid/params */
314 const uint8_t *digestData, /* signature over this digest */
315 size_t digestDataLen,/* length of digestData */
316 uint8_t *sig, /* signature, RETURNED */
317 size_t *sigLen); /* IN/OUT */
318
319 OSStatus SecKeyCopyPublicBytes(SecKeyRef key, CFDataRef* serializedPublic);
320 SecKeyRef SecKeyCreateFromPublicBytes(CFAllocatorRef allocator, CFIndex algorithmID, const uint8_t *keyData, CFIndex keyDataLength);
321 SecKeyRef SecKeyCreateFromPublicData(CFAllocatorRef allocator, CFIndex algorithmID, CFDataRef serialized);
322 CFDataRef SecKeyCopyPublicKeyHash(SecKeyRef key);
323
324 /* This function directly creates an iOS-format SecKeyRef from public key bytes. */
325 SecKeyRef SecKeyCreateRSAPublicKey_ios(CFAllocatorRef allocator,
326 const uint8_t *keyData, CFIndex keyDataLength,
327 SecKeyEncoding encoding);
328
329
330 CF_RETURNS_RETAINED
331 CFDictionaryRef SecKeyGeneratePrivateAttributeDictionary(SecKeyRef key,
332 CFTypeRef keyType,
333 CFDataRef privateBlob);
334 CF_RETURNS_RETAINED
335 CFDictionaryRef SecKeyGeneratePublicAttributeDictionary(SecKeyRef key, CFTypeRef keyType);
336 #endif // SEC_OS_IPHONE
337
338 enum {
339 kSecNullAlgorithmID = 0,
340 kSecRSAAlgorithmID = 1,
341 kSecDSAAlgorithmID = 2, /* unsupported, just here for reference. */
342 kSecECDSAAlgorithmID = 3,
343 };
344
345 #if SEC_OS_IPHONE_INCLUDES
346 /*!
347 @function SecKeyGetAlgorithmID
348 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
349 @param key A key reference.
350 @result An algorithm identifier.
351 @discussion Deprecated in iOS 9.0. Note that SecKeyGetAlgorithmID also exists on OS X
352 with different arguments for CDSA-based SecKeyRefs, and returns different values.
353 For compatibility, your code should migrate to use SecKeyGetAlgorithmId instead.
354 */
355 CFIndex SecKeyGetAlgorithmID(SecKeyRef key)
356 __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_2, __MAC_10_8, __IPHONE_5_0, __IPHONE_9_0);
357
358 /*!
359 @function SecKeyGetAlgorithmId
360 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
361 @param key A key reference.
362 @result An algorithm identifier.
363 */
364 CFIndex SecKeyGetAlgorithmId(SecKeyRef key)
365 __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_9_0);
366 #endif //#SEC_OS_IPHONE_INCLUDES
367
368 #if SEC_OS_IPHONE
369 typedef enum {
370 kSecKeyKeySizeInBits = 0,
371 kSecKeySignatureSize = 1,
372 kSecKeyEncryptedDataSize = 2,
373 // More might belong here, but we aren't settled on how
374 // to take into account padding and/or digest types.
375 } SecKeySize;
376
377 /*!
378 @function SecKeyGetSize
379 @abstract Returns a size in bytes.
380 @param key The key for which the block length is requested.
381 @param whichSize The size that you want evaluated.
382 @result The block length of the key in bytes.
383 @discussion If for example key is an RSA key the value returned by
384 this function is the size of the modulus.
385 */
386 size_t SecKeyGetSize(SecKeyRef key, SecKeySize whichSize)
387 __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);
388
389 #endif
390
391 #if SEC_OS_IPHONE
392
393 /*!
394 @function SecKeyLookupPersistentRef
395 @abstract Looks up a SecKeyRef via persistent ref.
396 @param persistentRef The persistent ref data for looking up.
397 @param lookedUpData retained SecKeyRef for the found object.
398 @result Errors when using SecItemFind for the persistent ref.
399 */
400 OSStatus SecKeyFindWithPersistentRef(CFDataRef persistentRef, SecKeyRef* lookedUpData)
401 __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0);
402 #endif // SEC_OS_IPHONE
403
404 /*!
405 @function SecKeyCopyPersistentRef
406 @abstract Gets a persistent reference for a key.
407 @param key Key to make a persistent ref for.
408 @param persistentRef Allocated data representing the persistent ref.
409 @result Errors when using SecItemFind for the persistent ref.
410 */
411 OSStatus SecKeyCopyPersistentRef(SecKeyRef key, CFDataRef* persistentRef)
412 __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0);
413
414 #if SEC_OS_IPHONE
415
416 /*
417 *
418 */
419
420 extern const CFStringRef _kSecKeyWrapPGPSymAlg; /* CFNumber */
421 extern const CFStringRef _kSecKeyWrapPGPFingerprint; /* CFDataRef, at least 20 bytes */
422 extern const CFStringRef _kSecKeyWrapPGPWrapAlg; /* kSecKeyWrapRFC6637WrapNNN, or any of the other PGP wrap algs */
423 extern const CFStringRef _kSecKeyWrapRFC6637Flags;
424 extern const CFStringRef _kSecKeyWrapRFC6637WrapDigestSHA256KekAES128;
425 extern const CFStringRef _kSecKeyWrapRFC6637WrapDigestSHA512KekAES256;
426
427 enum { kSecKeyWrapPGPFingerprintMinSize = 20 };
428 /*!
429 @function _SecKeyCopyWrapKey
430 @abstract Wrap a key
431 */
432
433 CFDataRef
434 _SecKeyCopyWrapKey(SecKeyRef key, SecKeyWrapType type, CFDataRef unwrappedKey, CFDictionaryRef parameters, CFDictionaryRef *outParam, CFErrorRef *error)
435 __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0);
436
437 /*!
438 @function _SecKeyWrapKey
439 @abstract Unwrap a key
440 */
441
442 CFDataRef
443 _SecKeyCopyUnwrapKey(SecKeyRef key, SecKeyWrapType type, CFDataRef wrappedKey, CFDictionaryRef parameters, CFDictionaryRef *outParam, CFErrorRef *error)
444 __OSX_AVAILABLE_STARTING(__MAC_10_10, __IPHONE_8_0);
445
446 #endif // SEC_OS_IPHONE
447
448
449 #if SEC_OS_OSX_INCLUDES
450 /*!
451 @function SecKeyGetAlgorithmID
452 @abstract Returns a pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure for the given key.
453 @param key A key reference.
454 @param algid On return, a pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure.
455 @result A result code. See "Security Error Codes" (SecBase.h).
456 @discussion Deprecated in OS X 10.8 and later. Continued use is strongly discouraged,
457 since there is a naming conflict with a similar function (also deprecated) on iOS that
458 had different arguments and a different return value. Use SecKeyGetAlgorithmId instead.
459 */
460 OSStatus SecKeyGetAlgorithmID(SecKeyRef key, const CSSM_X509_ALGORITHM_IDENTIFIER **algid)
461 DEPRECATED_IN_MAC_OS_X_VERSION_10_8_AND_LATER;
462
463 /*!
464 @function SecKeyGetAlgorithmId
465 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
466 @param key A key reference.
467 @result An algorithm identifier.
468 */
469 CFIndex SecKeyGetAlgorithmId(SecKeyRef key)
470 __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_9_0);
471
472 /*!
473 @function SecKeyGetStrengthInBits
474 @abstract Returns key strength in bits for the given key.
475 @param key A key reference.
476 @param algid A pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure, as returned from a call to SecKeyGetAlgorithmID.
477 @param strength On return, the key strength in bits.
478 @result A result code. See "Security Error Codes" (SecBase.h).
479 */
480 OSStatus SecKeyGetStrengthInBits(SecKeyRef key, const CSSM_X509_ALGORITHM_IDENTIFIER *algid, unsigned int *strength);
481
482 /*!
483 @function SecKeyImportPair
484 @abstract Takes an asymmetric key pair and stores it in the keychain specified by the keychain parameter.
485 @param keychainRef A reference to the keychain in which to store the private and public key items. Specify NULL for the default keychain.
486 @param publicCssmKey A CSSM_KEY which is valid for the CSP returned by SecKeychainGetCSPHandle(). This may be a normal key or reference key.
487 @param privateCssmKey A CSSM_KEY which is valid for the CSP returned by SecKeychainGetCSPHandle(). This may be a normal key or reference key.
488 @param initialAccess A SecAccess object that determines the initial access rights to the private key. The public key is given an any/any acl by default.
489 @param publicKey Optional output pointer to the keychain item reference of the imported public key. The caller must call CFRelease on this value if it is returned.
490 @param privateKey Optional output pointer to the keychain item reference of the imported private key. The caller must call CFRelease on this value if it is returned.
491 @result A result code. See "Security Error Codes" (SecBase.h).
492 @deprecated in 10.5 and later. Use the SecKeychainItemImport function instead; see <Security/SecImportExport.h>
493 */
494 OSStatus SecKeyImportPair(
495 SecKeychainRef keychainRef,
496 const CSSM_KEY *publicCssmKey,
497 const CSSM_KEY *privateCssmKey,
498 SecAccessRef initialAccess,
499 SecKeyRef* publicKey,
500 SecKeyRef* privateKey)
501 DEPRECATED_IN_MAC_OS_X_VERSION_10_5_AND_LATER;
502
503 /*!
504 @function SecKeyCreate
505 @abstract Create a key reference from the supplied key data.
506 @param allocator CFAllocator to allocate the key data. Pass NULL to use the default allocator.
507 @param keyClass A descriptor for the particular class of key that is being created.
508 @param keyData Data from which to create the key. Specify the format of this data in the encoding parameter.
509 @param keyDataLength Length of the data pointed to by keyData.
510 @param encoding A value of type SecKeyEncoding which describes the format of keyData.
511 @result A key reference.
512 @discussion Warning: this function is NOT intended for use outside the Security stack in its current state. <rdar://3201885>
513 IMPORTANT: on Mac OS X 10.5 and earlier, the SecKeyCreate function had a different parameter list.
514 The current parameter list matches the iPhone OS implementation. Existing clients of this function
515 on Mac OS X (and there should not be any outside the Security stack, per the warning above) must
516 migrate to the replacement function, SecKeyCreateWithCSSMKey.
517 */
518 SecKeyRef SecKeyCreate(CFAllocatorRef allocator,
519 const SecKeyDescriptor *keyClass, const uint8_t *keyData,
520 CFIndex keyDataLength, SecKeyEncoding encoding);
521
522 /*!
523 @function SecKeyCreateWithCSSMKey
524 @abstract Generate a temporary floating key reference for a CSSM_KEY.
525 @param key A pointer to a CSSM_KEY structure.
526 @param keyRef On return, a key reference.
527 @result A result code. See "Security Error Codes" (SecBase.h).
528 @discussion Warning: this function is NOT intended for use outside the Security stack in its current state. <rdar://3201885>
529 */
530 OSStatus SecKeyCreateWithCSSMKey(const CSSM_KEY *key, SecKeyRef* keyRef);
531
532
533 /*!
534 @function SecKeyRawSign
535 @abstract Given a private key and data to sign, generate a digital signature.
536 @param key Private key with which to sign.
537 @param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
538 @param dataToSign The data to be signed, typically the digest of the actual data.
539 @param dataToSignLen Length of dataToSign in bytes.
540 @param sig Pointer to buffer in which the signature will be returned.
541 @param sigLen IN/OUT maximum length of sig buffer on input, actualy length of sig on output.
542 @result A result code. See "Security Error Codes" (SecBase.h).
543 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
544 will be performed prior to signing. If this argument is kSecPaddingNone,
545 the incoming data will be signed "as is".
546
547 When PKCS1 padding is performed, the maximum length of data that can
548 be signed is the value returned by SecKeyGetBlockSize() - 11.
549
550 NOTE: The behavior this function with kSecPaddingNone is undefined if the
551 first byte of dataToSign is zero; there is no way to verify leading zeroes
552 as they are discarded during the calculation.
553
554 If you want to generate a proper PKCS1 style signature with DER encoding of
555 the digest type - and the dataToSign is a SHA1 digest - use kSecPaddingPKCS1SHA1.
556 */
557 OSStatus SecKeyRawSign(
558 SecKeyRef key,
559 SecPadding padding,
560 const uint8_t *dataToSign,
561 size_t dataToSignLen,
562 uint8_t *sig,
563 size_t *sigLen);
564
565
566 /*!
567 @function SecKeyRawVerify
568 @abstract Given a public key, data which has been signed, and a signature, verify the signature.
569 @param key Public key with which to verify the signature.
570 @param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
571 @param signedData The data over which sig is being verified, typically the digest of the actual data.
572 @param signedDataLen Length of signedData in bytes.
573 @param sig Pointer to the signature to verify.
574 @param sigLen Length of sig in bytes.
575 @result A result code. See "Security Error Codes" (SecBase.h).
576 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
577 will be checked during verification. If this argument is kSecPaddingNone,
578 the incoming data will be compared directly to sig.
579
580 If you are verifying a proper PKCS1-style signature, with DER encoding of the digest
581 type - and the signedData is a SHA1 digest - use kSecPaddingPKCS1SHA1.
582 */
583 OSStatus SecKeyRawVerify(
584 SecKeyRef key,
585 SecPadding padding,
586 const uint8_t *signedData,
587 size_t signedDataLen,
588 const uint8_t *sig,
589 size_t sigLen);
590
591
592 /*!
593 @function SecKeyEncrypt
594 @abstract Encrypt a block of plaintext.
595 @param key Public key with which to encrypt the data.
596 @param padding See Padding Types above, typically kSecPaddingPKCS1.
597 @param plainText The data to encrypt.
598 @param plainTextLen Length of plainText in bytes, this must be less
599 or equal to the value returned by SecKeyGetBlockSize().
600 @param cipherText Pointer to the output buffer.
601 @param cipherTextLen On input, specifies how much space is available at
602 cipherText; on return, it is the actual number of cipherText bytes written.
603 @result A result code. See "Security Error Codes" (SecBase.h).
604 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
605 will be performed prior to encryption. If this argument is kSecPaddingNone,
606 the incoming data will be encrypted "as is".
607
608 When PKCS1 padding is performed, the maximum length of data that can
609 be encrypted is the value returned by SecKeyGetBlockSize() - 11.
610
611 When memory usage is a critical issue, note that the input buffer
612 (plainText) can be the same as the output buffer (cipherText).
613 */
614 OSStatus SecKeyEncrypt(
615 SecKeyRef key,
616 SecPadding padding,
617 const uint8_t *plainText,
618 size_t plainTextLen,
619 uint8_t *cipherText,
620 size_t *cipherTextLen);
621
622
623 /*!
624 @function SecKeyDecrypt
625 @abstract Decrypt a block of ciphertext.
626 @param key Private key with which to decrypt the data.
627 @param padding See SecPadding types above; typically kSecPaddingPKCS1.
628 @param cipherText The data to decrypt.
629 @param cipherTextLen Length of cipherText in bytes; this must be less
630 or equal to the value returned by SecKeyGetBlockSize().
631 @param plainText Pointer to the output buffer.
632 @param plainTextLen On input, specifies how much space is available at
633 plainText; on return, it is the actual number of plainText bytes written.
634 @result A result code. See "Security Error Codes" (SecBase.h).
635 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
636 will be removed after decryption. If this argument is kSecPaddingNone,
637 the decrypted data will be returned "as is".
638
639 When memory usage is a critical issue, note that the input buffer
640 (plainText) can be the same as the output buffer (cipherText).
641 */
642 OSStatus SecKeyDecrypt(
643 SecKeyRef key, /* Private key */
644 SecPadding padding, /* kSecPaddingNone, kSecPaddingPKCS1, kSecPaddingOAEP */
645 const uint8_t *cipherText,
646 size_t cipherTextLen, /* length of cipherText */
647 uint8_t *plainText,
648 size_t *plainTextLen); /* IN/OUT */
649
650 OSStatus SecKeyVerifyDigest(
651 SecKeyRef key, /* Private key */
652 const SecAsn1AlgId *algId, /* algorithm oid/params */
653 const uint8_t *digestData, /* signature over this digest */
654 size_t digestDataLen, /* length of dataToDigest */
655 const uint8_t *sig, /* signature to verify */
656 size_t sigLen); /* length of sig */
657
658 OSStatus SecKeySignDigest(
659 SecKeyRef key, /* Private key */
660 const SecAsn1AlgId *algId, /* algorithm oid/params */
661 const uint8_t *digestData, /* signature over this digest */
662 size_t digestDataLen, /* length of digestData */
663 uint8_t *sig, /* signature, RETURNED */
664 size_t *sigLen); /* IN/OUT */
665
666
667 /* These are the named curves we support. These values come from RFC 4492
668 section 5.1.1, with the exception of SSL_Curve_None which means
669 "ECDSA not negotiated". */
670 typedef enum
671 {
672 kSecECCurveNone = -1,
673 kSecECCurveSecp256r1 = 23,
674 kSecECCurveSecp384r1 = 24,
675 kSecECCurveSecp521r1 = 25
676 } SecECNamedCurve;
677
678 /* Return a named curve enum for ecPrivateKey. */
679 SecECNamedCurve SecECKeyGetNamedCurve(SecKeyRef ecPrivateKey);
680 CFDataRef SecECKeyCopyPublicBits(SecKeyRef key);
681
682 /* Given an RSA public key in encoded form return a SecKeyRef representing
683 that key. Supported encodings are kSecKeyEncodingPkcs1. */
684 SecKeyRef SecKeyCreateRSAPublicKey(CFAllocatorRef allocator,
685 const uint8_t *keyData, CFIndex keyDataLength,
686 SecKeyEncoding encoding);
687
688 CFDataRef SecKeyCopyModulus(SecKeyRef rsaPublicKey);
689 CFDataRef SecKeyCopyExponent(SecKeyRef rsaPublicKey);
690
691 /*!
692 @function SecKeyCopyPublicBytes
693 @abstract Gets the bits of a public key
694 @param key Key to retrieve the bits.
695 @param publicBytes An out parameter to receive the public key bits
696 @result Errors if any when retrieving the public key bits..
697 */
698 OSStatus SecKeyCopyPublicBytes(SecKeyRef key, CFDataRef* publicBytes);
699
700 /*!
701 @function SecKeyCreatePublicFromPrivate
702 @abstract Create a public SecKeyRef from a private SecKeyRef
703 @param privateKey The private SecKeyRef for which you want the public key
704 @result A public SecKeyRef, or NULL if the conversion failed
705 @discussion This is a "best attempt" function, hence the SPI nature. If the public
706 key bits are not in memory, it attempts to load from the keychain. If the public
707 key was not tracked on the keychain, it will fail.
708 */
709 SecKeyRef SecKeyCreatePublicFromPrivate(SecKeyRef privateKey);
710
711 /*!
712 @function SecKeyCreateFromPublicData
713 */
714 SecKeyRef SecKeyCreateFromPublicData(CFAllocatorRef allocator, CFIndex algorithmID, CFDataRef publicBytes);
715
716 OSStatus SecKeyRawVerifyOSX(
717 SecKeyRef key,
718 SecPadding padding,
719 const uint8_t *signedData,
720 size_t signedDataLen,
721 const uint8_t *sig,
722 size_t sigLen);
723
724 #endif // SEC_OS_OSX_INCLUDES
725
726 /*!
727 @enum SecKeyAttestationKeyType
728 @abstract Defines types of builtin attestation keys.
729 */
730 typedef CF_ENUM(uint32_t, SecKeyAttestationKeyType)
731 {
732 kSecKeyAttestationKeyTypeSIK = 0,
733 kSecKeyAttestationKeyTypeGID
734 } __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
735
736 /*!
737 @function SecKeyCopyAttestationKey
738 @abstract Returns a copy of a builtin attestation key.
739
740 @param keyType Type of the requested builtin key.
741 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
742
743 @result On success a SecKeyRef containing the requested key is returned, on failure it returns NULL.
744 */
745 SecKeyRef SecKeyCopyAttestationKey(SecKeyAttestationKeyType keyType, CFErrorRef *error)
746 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
747
748 /*!
749 @function SecKeyCreateAttestation
750 @abstract Attests a key with another key.
751
752 @param key The attesting key.
753 @param keyToAttest The key which is to be attested.
754 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
755
756 @result On success a CFDataRef containing the attestation data is returned, on failure it returns NULL.
757
758 @discussion Key attestation only works for CTK SEP keys, i.e. keys created with kSecAttrTokenID=kSecAttrTokenIDSecureEnclave.
759 */
760 CFDataRef SecKeyCreateAttestation(SecKeyRef key, SecKeyRef keyToAttest, CFErrorRef *error)
761 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
762
763 /*!
764 @function SecKeySetParameter
765 @abstract Sets unspecified key parameter for the backend.
766
767 @param key Key to set the parameter to.
768 @param name Identifies parameter to be set.
769 @param value New value for the parameter.
770 @param error Error which gathers more information when something went wrong.
771
772 @discussion Serves as channel between SecKey client and backend for passing additional sideband data send from SecKey caller
773 to SecKey implementation backend. Parameter names and types are either generic kSecUse*** attributes or are a contract between
774 SecKey user (application) and backend and in this case are not interpreted by SecKey layer in any way.
775 */
776 Boolean SecKeySetParameter(SecKeyRef key, CFStringRef name, CFPropertyListRef value, CFErrorRef *error)
777 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
778
779 extern const CFStringRef kSecKeyParameterSETokenAttestationNonce
780 API_AVAILABLE(macos(10.13), ios(11.0), tvos(11.0), watchos(4.0));
781
782 /*!
783 @function SecKeyCreateDuplicate
784 @abstract Creates duplicate fo the key.
785
786 @param key Source key to be duplicated
787
788 @discussion Only memory representation of the key is duplicated, so if the key is backed by keychain, only one instance
789 stays in the keychain. Duplicating key is useful for setting 'temporary' key parameters using SecKeySetParameter.
790 If the key is immutable (i.e. does not support SecKeySetParameter), calling this method is identical to calling CFRetain().
791 */
792 SecKeyRef SecKeyCreateDuplicate(SecKeyRef key)
793 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
794
795 /*!
796 Algorithms for converting between bigendian and core-crypto ccunit data representation.
797 */
798 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureRawCCUnit;
799 extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionRawCCUnit;
800
801 /*!
802 Internal algorithm for RSA-MD5. We do not want to export MD5 in new API, but we need it
803 for implementing legacy interfaces.
804 */
805 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15MD5;
806 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15MD5;
807
808 /*!
809 Algorithms for interoperability with libaks smartcard support.
810 */
811 extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionAKSSmartCard;
812
813 __END_DECLS
814
815 #endif /* !_SECURITY_SECKEYPRIV_H_ */