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