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