2 * Copyright (c) 2006-2010,2012-2015 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
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.
30 You can use a key as a keychain item in most functions.
33 #ifndef _SECURITY_SECKEYPRIV_H_
34 #define _SECURITY_SECKEYPRIV_H_
36 #include <Security/SecBase.h>
37 #include <Security/SecKey.h>
38 #include <Security/SecAsn1Types.h>
39 #include <CoreFoundation/CFRuntime.h>
42 #include <Security/x509defs.h>
46 #include <Security/SecKey.h>
47 #include <AvailabilityMacros.h>
52 typedef struct __SecDERKey
{
57 CFIndex parametersLength
;
59 /* Contents of BIT STRING in DER Encoding */
64 typedef struct SecRSAPublicKeyParams
{
65 uint8_t *modulus
; /* modulus */
66 CFIndex modulusLength
;
67 uint8_t *exponent
; /* public exponent */
68 CFIndex exponentLength
;
69 } SecRSAPublicKeyParams
;
71 typedef uint32_t SecKeyEncoding
;
73 /* Typically only used for symmetric keys. */
74 kSecKeyEncodingRaw
= 0,
76 /* RSA keys are DER-encoded according to PKCS1. */
77 kSecKeyEncodingPkcs1
= 1,
79 /* RSA keys are DER-encoded according to PKCS1 with Apple Extensions. */
80 kSecKeyEncodingApplePkcs1
= 2,
82 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
83 to a SecRSAPublicKeyParams and keyDataLength is
84 sizeof(SecRSAPublicKeyParams). */
85 kSecKeyEncodingRSAPublicParams
= 3,
87 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
88 to a SecRSAPublicKeyParams and keyDataLength is
89 sizeof(SecRSAPublicKeyParams). */
90 kSecDERKeyEncoding
= 4,
92 /* Internal "encodings to send other data" */
94 kSecExtractPublicFromPrivate
= 6,
96 /* Encoding came from SecKeyCopyPublicBytes for a public key,
97 or internally from a private key */
98 kSecKeyEncodingBytes
= 7,
100 /* Handing in a private key from corecrypto directly. */
101 kSecKeyCoreCrypto
= 8,
105 typedef uint32_t SecKeyWrapType
;
107 /* wrap key in RFC3394 (AESWrap) */
108 kSecKeyWrapRFC3394
= 0,
110 /* wrap key in PGP style (support EC keys only right now) */
111 kSecKeyWrapPublicKeyPGP
= 1,
115 typedef CF_ENUM(CFIndex
, SecKeyOperationMode
) {
116 kSecKeyOperationModePerform
= 0,
117 kSecKeyOperationModeCheckIfSupported
= 1,
120 typedef OSStatus (*SecKeyInitMethod
)(SecKeyRef
, const uint8_t *, CFIndex
,
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
);
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
);
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.
164 typedef CFTypeRef(*SecKeyCopyOperationResultMethod
)(SecKeyRef key
, SecKeyOperationType operation
, SecKeyAlgorithm algorithm
, CFArrayRef allAlgorithms
, SecKeyOperationMode mode
, CFTypeRef in1
, CFTypeRef in2
, CFErrorRef
*error
);
166 #define kSecKeyDescriptorVersion (4)
168 typedef struct __SecKeyDescriptor
{
169 /* Version of this SecKeyDescriptor. Must be kSecKeyDescriptorVersion. */
172 /* Name of this key class for use by SecKeyShow(). */
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. */
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
;
205 #if kSecKeyDescriptorVersion > 1
206 SecKeyCopyPublicBytesMethod copyPublic
;
208 #if kSecKeyDescriptorVersion > 2
209 SecKeyCopyWrapKeyMethod copyWrapKey
;
210 SecKeyCopyUnwrapKeyMethod copyUnwrapKey
;
212 #if kSecKeyDescriptorVersion > 3
213 SecKeyCopyExternalRepresentationMethod copyExternalRepresentation
;
214 SecKeyCopyPublicKeyMethod copyPublicKey
;
215 SecKeyCopyOperationResultMethod copyOperationResult
;
216 SecKeyIsEqualMethod isEqual
;
217 SecKeyCreateDuplicateMethod createDuplicate
;
218 SecKeySetParameterMethod setParameter
;
225 const SecKeyDescriptor
*key_class
;
227 /* The actual key handled by class. */
231 /* Create a public key from a CFData containing a SubjectPublicKeyInfo in DER format. */
232 SecKeyRef
SecKeyCreateFromSubjectPublicKeyInfoData(CFAllocatorRef allocator
,
233 CFDataRef subjectPublicKeyInfoData
);
235 /* Crete a SubjectPublicKeyInfo in DER format from a SecKey */
236 CFDataRef
SecKeyCopySubjectPublicKeyInfo(SecKeyRef key
);
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.
249 SecKeyRef
SecKeyCreate(CFAllocatorRef allocator
,
250 const SecKeyDescriptor
*key_class
, const uint8_t *keyData
,
251 CFIndex keyDataLength
, SecKeyEncoding encoding
);
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
);
258 /* Create public key from private key */
259 SecKeyRef
SecKeyCreatePublicFromPrivate(SecKeyRef privateKey
);
261 /* Get Private Key (if present) by publicKey. */
262 SecKeyRef
SecKeyCopyMatchingPrivateKey(SecKeyRef publicKey
, CFErrorRef
*error
);
264 OSStatus
SecKeyGetMatchingPrivateKeyStatus(SecKeyRef publicKey
, CFErrorRef
*error
);
265 CFDataRef
SecKeyCreatePersistentRefToMatchingPrivateKey(SecKeyRef publicKey
, CFErrorRef
*error
);
267 /* Return an attribute dictionary used to find a private key by public key hash */
268 CFDictionaryRef
CreatePrivateKeyMatchingQuery(SecKeyRef publicKey
, bool returnPersistentRef
);
270 /* Return a key from an attribute dictionary that was used to store this item
272 SecKeyRef
SecKeyCreateFromAttributeDictionary(CFDictionaryRef refAttributes
);
274 // SecAsn1AlgId is deprecated, but we still need to use it.
275 #pragma clang diagnostic push
276 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
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 */
286 /* Return an attribute dictionary used to store this item in a keychain. */
287 CFDictionaryRef
SecKeyCopyAttributeDictionary(SecKeyRef key
);
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 */
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 */
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 */
313 #pragma clang diagnostic pop
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
);
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
);
327 CFDictionaryRef
SecKeyGeneratePrivateAttributeDictionary(SecKeyRef key
,
329 CFDataRef privateBlob
);
331 CFDictionaryRef
SecKeyGeneratePublicAttributeDictionary(SecKeyRef key
, CFTypeRef keyType
);
334 kSecNullAlgorithmID
= 0,
335 kSecRSAAlgorithmID
= 1,
336 kSecDSAAlgorithmID
= 2, /* unsupported, just here for reference. */
337 kSecECDSAAlgorithmID
= 3,
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.
346 CFIndex
SecKeyGetAlgorithmId(SecKeyRef key
)
347 SPI_AVAILABLE(macos(10.8), ios(9.0));
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.
359 CFIndex
SecKeyGetAlgorithmID(SecKeyRef key
)
360 API_DEPRECATED_WITH_REPLACEMENT("SecKeyGetAlgorithmId", ios(5.0, 9.0)) API_UNAVAILABLE(iosmac
);
361 #endif // TARGET_OS_IPHONE
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.
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
, iosmac
);
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.
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.
396 size_t SecKeyGetSize(SecKeyRef key
, SecKeySize whichSize
)
397 __OSX_AVAILABLE_STARTING(__MAC_10_8
, __IPHONE_5_0
);
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.
407 OSStatus
SecKeyFindWithPersistentRef(CFDataRef persistentRef
, SecKeyRef
* lookedUpData
)
408 __OSX_AVAILABLE_STARTING(__MAC_10_9
, __IPHONE_7_0
);
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.
417 OSStatus
SecKeyCopyPersistentRef(SecKeyRef key
, CFDataRef
* persistentRef
)
418 __OSX_AVAILABLE_STARTING(__MAC_10_9
, __IPHONE_7_0
);
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
;
427 enum { kSecKeyWrapPGPFingerprintMinSize
= 20 };
429 @function _SecKeyCopyWrapKey
434 _SecKeyCopyWrapKey(SecKeyRef key
, SecKeyWrapType type
, CFDataRef unwrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
)
435 __OSX_AVAILABLE_STARTING(__MAC_10_10
, __IPHONE_8_0
);
438 @function _SecKeyWrapKey
439 @abstract Unwrap a key
443 _SecKeyCopyUnwrapKey(SecKeyRef key
, SecKeyWrapType type
, CFDataRef wrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
)
444 __OSX_AVAILABLE_STARTING(__MAC_10_10
, __IPHONE_8_0
);
446 #if SEC_OS_OSX_INCLUDES
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).
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));
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>
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
, iosmac
);
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.
493 SecKeyRef
SecKeyCreate(CFAllocatorRef allocator
,
494 const SecKeyDescriptor
*keyClass
, const uint8_t *keyData
,
495 CFIndex keyDataLength
, SecKeyEncoding encoding
);
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>
505 OSStatus
SecKeyCreateWithCSSMKey(const CSSM_KEY
*key
, SecKeyRef
* keyRef
) API_DEPRECATED("CSSM_KEY is deprecated", macos(10.11, 10.14));
507 // Alias macOS versions of this deprecated SPI to unique macOS names. Undecorated names are used for iosmac.
508 #define SecKeyRawSign SecKeyRawSign_macOS
509 #define SecKeyRawVerify SecKeyRawVerify_macOS
511 CF_IMPLICIT_BRIDGING_ENABLED
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".
527 When PKCS1 padding is performed, the maximum length of data that can
528 be signed is the value returned by SecKeyGetBlockSize() - 11.
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.
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.
537 OSStatus
SecKeyRawSign(
540 const uint8_t *dataToSign
,
541 size_t dataToSignLen
,
544 SPI_DEPRECATED_WITH_REPLACEMENT("SecKeyCreateSignature", macos(10.7, 10.15));
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.
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.
564 OSStatus
SecKeyRawVerify(
567 const uint8_t *signedData
,
568 size_t signedDataLen
,
571 SPI_DEPRECATED_WITH_REPLACEMENT("SecKeyVerifySignature", macos(10.7, 10.15));
573 CF_IMPLICIT_BRIDGING_DISABLED
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".
591 When PKCS1 padding is performed, the maximum length of data that can
592 be encrypted is the value returned by SecKeyGetBlockSize() - 11.
594 When memory usage is a critical issue, note that the input buffer
595 (plainText) can be the same as the output buffer (cipherText).
597 OSStatus
SecKeyEncrypt(
600 const uint8_t *plainText
,
603 size_t *cipherTextLen
)
604 SPI_DEPRECATED_WITH_REPLACEMENT("SecKeyCreateEncryptedData", macos(10.7, 10.15));
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".
623 When memory usage is a critical issue, note that the input buffer
624 (plainText) can be the same as the output buffer (cipherText).
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 */
632 size_t *plainTextLen
) /* IN/OUT */
633 SPI_DEPRECATED_WITH_REPLACEMENT("SecKeyCreateDecryptedData", macos(10.7, 10.15));
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 */
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
655 #endif // SEC_OS_OSX_INCLUDES
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". */
663 kSecECCurveNone
= -1,
664 kSecECCurveSecp256r1
= 23,
665 kSecECCurveSecp384r1
= 24,
666 kSecECCurveSecp521r1
= 25
669 /* Return a named curve enum for ecPrivateKey. */
670 SecECNamedCurve
SecECKeyGetNamedCurve(SecKeyRef ecPrivateKey
);
671 CFDataRef
SecECKeyCopyPublicBits(SecKeyRef key
);
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
);
679 CFDataRef
SecKeyCopyModulus(SecKeyRef rsaPublicKey
);
680 CFDataRef
SecKeyCopyExponent(SecKeyRef rsaPublicKey
);
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..
689 OSStatus
SecKeyCopyPublicBytes(SecKeyRef key
, CFDataRef
* publicBytes
);
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.
700 SecKeyRef
SecKeyCreatePublicFromPrivate(SecKeyRef privateKey
);
703 @function SecKeyCreateFromPublicData
705 SecKeyRef
SecKeyCreateFromPublicData(CFAllocatorRef allocator
, CFIndex algorithmID
, CFDataRef publicBytes
);
707 #if SEC_OS_OSX_INCLUDES
708 OSStatus
SecKeyRawVerifyOSX(
711 const uint8_t *signedData
,
712 size_t signedDataLen
,
715 SPI_DEPRECATED_WITH_REPLACEMENT("SecKeyVerifySignature", macos(10.7, 10.15));
717 #endif // SEC_OS_OSX_INCLUDES
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.
723 extern const CFStringRef kSecKeyApplePayEnabled
724 SPI_AVAILABLE(macos(10.14.4), ios(12.2), tvos(12.2), watchos(5.2));
727 @constant kSecKeyEncryptionParameterSymmetricKeySizeInBits CFNumberRef with size in bits for ephemeral
728 symmetric key used for encryption/decryption.
730 extern const CFStringRef kSecKeyEncryptionParameterSymmetricKeySizeInBits
731 SPI_AVAILABLE(macos(10.14.4), ios(12.2), tvos(12.2), watchos(5.2));
734 @constant kSecKeyEncryptionParameterSymmetricAAD CFDataRef with additional authentiction data for AES-GCM encryption.
736 extern const CFStringRef kSecKeyEncryptionParameterSymmetricAAD
737 SPI_AVAILABLE(macos(10.14.4), ios(12.2), tvos(12.2), watchos(5.2));
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.
744 extern const CFStringRef kSecKeyEncryptionParameterRecryptParameters
745 SPI_AVAILABLE(macos(10.14.4), ios(12.2), tvos(12.2), watchos(5.2));
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.
753 extern const CFStringRef kSecKeyEncryptionParameterRecryptCertificate
754 SPI_AVAILABLE(macos(10.14.4), ios(12.2), tvos(12.2), watchos(5.2));
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.
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));
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.
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.
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));
802 @enum SecKeyAttestationKeyType
803 @abstract Defines types of builtin attestation keys.
805 typedef CF_ENUM(uint32_t, SecKeyAttestationKeyType
)
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 } SPI_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
815 @function SecKeyCopyAttestationKey
816 @abstract Returns a copy of a builtin attestation key.
818 @param keyType Type of the requested builtin key.
819 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
821 @result On success a SecKeyRef containing the requested key is returned, on failure it returns NULL.
823 SecKeyRef
SecKeyCopyAttestationKey(SecKeyAttestationKeyType keyType
, CFErrorRef
*error
)
824 SPI_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
827 @function SecKeyCreateAttestation
828 @abstract Attests a key with another key.
830 @param key The attesting key.
831 @param keyToAttest The key which is to be attested.
832 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
834 @result On success a CFDataRef containing the attestation data is returned, on failure it returns NULL.
836 @discussion Key attestation only works for CTK SEP keys, i.e. keys created with kSecAttrTokenID=kSecAttrTokenIDSecureEnclave.
838 CFDataRef
SecKeyCreateAttestation(SecKeyRef key
, SecKeyRef keyToAttest
, CFErrorRef
*error
)
839 SPI_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
842 @function SecKeySetParameter
843 @abstract Sets unspecified key parameter for the backend.
845 @param key Key to set the parameter to.
846 @param name Identifies parameter to be set.
847 @param value New value for the parameter.
848 @param error Error which gathers more information when something went wrong.
850 @discussion Serves as channel between SecKey client and backend for passing additional sideband data send from SecKey caller
851 to SecKey implementation backend. Parameter names and types are either generic kSecUse*** attributes or are a contract between
852 SecKey user (application) and backend and in this case are not interpreted by SecKey layer in any way.
854 Boolean
SecKeySetParameter(SecKeyRef key
, CFStringRef name
, CFPropertyListRef value
, CFErrorRef
*error
)
855 SPI_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
857 extern const CFStringRef kSecKeyParameterSETokenAttestationNonce
858 SPI_AVAILABLE(macos(10.13), ios(11.0), tvos(11.0), watchos(4.0));
861 Available lifetime operations for SEP system keys.
863 typedef CF_ENUM(int, SecKeyControlLifetimeType
) {
864 kSecKeyControlLifetimeTypeBump
= 0,
865 kSecKeyControlLifetimeTypeCommit
= 1,
866 } SPI_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0));
869 @function SecKeyControlLifetime
870 @abstract Performs key lifetime control operations for SEP system keys.
872 @param key Key to be controlled, currently must be either proposed or committed system UIK.
873 @param type Type of the control operation to be performed.
874 @param error Error which gathers more information when something went wrong.
876 Boolean
SecKeyControlLifetime(SecKeyRef key
, SecKeyControlLifetimeType type
, CFErrorRef
*error
)
877 SPI_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0));
880 @function SecKeyCreateDuplicate
881 @abstract Creates duplicate fo the key.
883 @param key Source key to be duplicated
885 @discussion Only memory representation of the key is duplicated, so if the key is backed by keychain, only one instance
886 stays in the keychain. Duplicating key is useful for setting 'temporary' key parameters using SecKeySetParameter.
887 If the key is immutable (i.e. does not support SecKeySetParameter), calling this method is identical to calling CFRetain().
889 SecKeyRef
SecKeyCreateDuplicate(SecKeyRef key
)
890 SPI_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
893 Algorithms for converting between bigendian and core-crypto ccunit data representation.
895 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureRawCCUnit
;
896 extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionRawCCUnit
;
899 Internal algorithm for RSA-MD5. We do not want to export MD5 in new API, but we need it
900 for implementing legacy interfaces.
902 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15MD5
;
903 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15MD5
;
906 Algorithms for interoperability with libaks smartcard support.
908 extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionAKSSmartCard
;
912 #endif /* !_SECURITY_SECKEYPRIV_H_ */