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/SecKey.h>
43 #include <Security/x509defs.h>
44 #include <AvailabilityMacros.h>
49 typedef struct __SecDERKey
{
54 CFIndex parametersLength
;
56 /* Contents of BIT STRING in DER Encoding */
61 typedef struct SecRSAPublicKeyParams
{
62 uint8_t *modulus
; /* modulus */
63 CFIndex modulusLength
;
64 uint8_t *exponent
; /* public exponent */
65 CFIndex exponentLength
;
66 } SecRSAPublicKeyParams
;
68 typedef uint32_t SecKeyEncoding
;
70 /* Typically only used for symmetric keys. */
71 kSecKeyEncodingRaw
= 0,
73 /* RSA keys are DER-encoded according to PKCS1. */
74 kSecKeyEncodingPkcs1
= 1,
76 /* RSA keys are DER-encoded according to PKCS1 with Apple Extensions. */
77 kSecKeyEncodingApplePkcs1
= 2,
79 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
80 to a SecRSAPublicKeyParams and keyDataLength is
81 sizeof(SecRSAPublicKeyParams). */
82 kSecKeyEncodingRSAPublicParams
= 3,
84 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
85 to a SecRSAPublicKeyParams and keyDataLength is
86 sizeof(SecRSAPublicKeyParams). */
87 kSecDERKeyEncoding
= 4,
89 /* Internal "encodings to send other data" */
91 kSecExtractPublicFromPrivate
= 6,
93 /* Encoding came from SecKeyCopyPublicBytes for a public key,
94 or internally from a private key */
95 kSecKeyEncodingBytes
= 7,
97 /* Handing in a private key from corecrypto directly. */
98 kSecKeyCoreCrypto
= 8,
102 typedef uint32_t SecKeyWrapType
;
104 /* wrap key in RFC3394 (AESWrap) */
105 kSecKeyWrapRFC3394
= 0,
107 /* wrap key in PGP style (support EC keys only right now) */
108 kSecKeyWrapPublicKeyPGP
= 1,
112 typedef CF_ENUM(CFIndex
, SecKeyOperationMode
) {
113 kSecKeyOperationModePerform
= 0,
114 kSecKeyOperationModeCheckIfSupported
= 1,
117 typedef OSStatus (*SecKeyInitMethod
)(SecKeyRef
, const uint8_t *, CFIndex
,
119 typedef void (*SecKeyDestroyMethod
)(SecKeyRef
);
120 typedef OSStatus (*SecKeyRawSignMethod
)(SecKeyRef key
, SecPadding padding
,
121 const uint8_t *dataToSign
, size_t dataToSignLen
,
122 uint8_t *sig
, size_t *sigLen
);
123 typedef OSStatus (*SecKeyRawVerifyMethod
)(
124 SecKeyRef key
, SecPadding padding
, const uint8_t *signedData
,
125 size_t signedDataLen
, const uint8_t *sig
, size_t sigLen
);
126 typedef OSStatus (*SecKeyEncryptMethod
)(SecKeyRef key
, SecPadding padding
,
127 const uint8_t *plainText
, size_t plainTextLen
,
128 uint8_t *cipherText
, size_t *cipherTextLen
);
129 typedef OSStatus (*SecKeyDecryptMethod
)(SecKeyRef key
, SecPadding padding
,
130 const uint8_t *cipherText
, size_t cipherTextLen
,
131 uint8_t *plainText
, size_t *plainTextLen
);
132 typedef OSStatus (*SecKeyComputeMethod
)(SecKeyRef key
,
133 const uint8_t *pub_key
, size_t pub_key_len
,
134 uint8_t *computed_key
, size_t *computed_key_len
);
135 typedef size_t (*SecKeyBlockSizeMethod
)(SecKeyRef key
);
136 typedef CFDictionaryRef (*SecKeyCopyDictionaryMethod
)(SecKeyRef key
);
137 typedef CFIndex (*SecKeyGetAlgorithmIDMethod
)(SecKeyRef key
);
138 typedef OSStatus (*SecKeyCopyPublicBytesMethod
)(SecKeyRef key
, CFDataRef
*serialization
);
139 typedef CFDataRef (*SecKeyCopyWrapKeyMethod
)(SecKeyRef key
, SecKeyWrapType type
, CFDataRef unwrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
);
140 typedef CFDataRef (*SecKeyCopyUnwrapKeyMethod
)(SecKeyRef key
, SecKeyWrapType type
, CFDataRef wrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
);
141 typedef CFStringRef (*SecKeyDescribeMethod
)(SecKeyRef key
);
143 typedef CFDataRef (*SecKeyCopyExternalRepresentationMethod
)(SecKeyRef key
, CFErrorRef
*error
);
144 typedef SecKeyRef (*SecKeyCopyPublicKeyMethod
)(SecKeyRef key
);
145 typedef Boolean (*SecKeyIsEqualMethod
)(SecKeyRef key1
, SecKeyRef key2
);
146 typedef SecKeyRef (*SecKeyCreateDuplicateMethod
)(SecKeyRef key
);
147 typedef Boolean (*SecKeySetParameterMethod
)(SecKeyRef key
, CFStringRef name
, CFPropertyListRef value
, CFErrorRef
*error
);
150 @abstract Performs cryptographic operation with the key.
151 @param key Key to perform the operation on.
152 @param operation Type of operation to be performed.
153 @param algorithm Algorithm identifier for the operation. Determines format of input and output data.
154 @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.
155 @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.
156 @param in1 First input parameter for the operation, meaningful only in ModePerform.
157 @param in2 Second input parameter for the operation, meaningful only in ModePerform.
158 @param error Error details when NULL is returned.
159 @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.
161 typedef CFTypeRef(*SecKeyCopyOperationResultMethod
)(SecKeyRef key
, SecKeyOperationType operation
, SecKeyAlgorithm algorithm
, CFArrayRef allAlgorithms
, SecKeyOperationMode mode
, CFTypeRef in1
, CFTypeRef in2
, CFErrorRef
*error
);
163 #define kSecKeyDescriptorVersion (4)
165 typedef struct __SecKeyDescriptor
{
166 /* Version of this SecKeyDescriptor. Must be kSecKeyDescriptorVersion. */
169 /* Name of this key class for use by SecKeyShow(). */
172 /* If nonzero, SecKeyCreate will allocate this many bytes for the key
173 field in the SecKeyRef it creates. If zero key is NULL and the
174 implementor can choose to dynamically allocate it in the init
175 function and free it in the destroy function. */
178 /* Called by SecKeyCreate(). */
179 SecKeyInitMethod init
;
180 /* Called by destructor (final CFRelease() or gc if using). */
181 SecKeyDestroyMethod destroy
;
182 /* Called by SecKeyRawSign(). */
183 SecKeyRawSignMethod rawSign
;
184 /* Called by SecKeyRawVerify(). */
185 SecKeyRawVerifyMethod rawVerify
;
186 /* Called by SecKeyEncrypt(). */
187 SecKeyEncryptMethod encrypt
;
188 /* Called by SecKeyDecrypt(). */
189 SecKeyDecryptMethod decrypt
;
190 /* Reserved for future use. */
191 SecKeyComputeMethod compute
;
192 /* Called by SecKeyGetBlockSize(). */
193 SecKeyBlockSizeMethod blockSize
;
194 /* Called by SecKeyCopyAttributeDictionary(), which is private. */
195 SecKeyCopyDictionaryMethod copyDictionary
;
196 /* Called by SecKeyDescribeMethod(). */
197 SecKeyDescribeMethod describe
;
198 #if kSecKeyDescriptorVersion > 0
199 /* Called by SecKeyCopyAttributeDictionary(), which is private. */
200 SecKeyGetAlgorithmIDMethod getAlgorithmID
;
202 #if kSecKeyDescriptorVersion > 1
203 SecKeyCopyPublicBytesMethod copyPublic
;
205 #if kSecKeyDescriptorVersion > 2
206 SecKeyCopyWrapKeyMethod copyWrapKey
;
207 SecKeyCopyUnwrapKeyMethod copyUnwrapKey
;
209 #if kSecKeyDescriptorVersion > 3
210 SecKeyCopyExternalRepresentationMethod copyExternalRepresentation
;
211 SecKeyCopyPublicKeyMethod copyPublicKey
;
212 SecKeyCopyOperationResultMethod copyOperationResult
;
213 SecKeyIsEqualMethod isEqual
;
214 SecKeyCreateDuplicateMethod createDuplicate
;
215 SecKeySetParameterMethod setParameter
;
222 const SecKeyDescriptor
*key_class
;
225 // On OSX, keep optional SecKeyRef which holds dynamically, on-demand created CSSM-based key with the same
226 // key material. It is used to implement SecKeyGetCSSMKey().
230 /* The actual key handled by class. */
234 /* Create a public key from a CFData containing a SubjectPublicKeyInfo in DER format. */
235 SecKeyRef
SecKeyCreateFromSubjectPublicKeyInfoData(CFAllocatorRef allocator
,
236 CFDataRef subjectPublicKeyInfoData
);
238 /* Crete a SubjectPublicKeyInfo in DER format from a SecKey */
239 CFDataRef
SecKeyCopySubjectPublicKeyInfo(SecKeyRef key
);
243 @function SecKeyCreate
244 @abstract Given a private key and data to sign, generate a digital signature.
245 @param allocator allocator to use when allocating this key instance.
246 @param key_class pointer to a SecKeyDescriptor.
247 @param keyData The second argument to the init() function in the key_class.
248 @param keyDataLength The third argument to the init() function in the key_class.
249 @param encoding The fourth argument to the init() function in the key_class.
250 @result A newly allocated SecKeyRef.
252 SecKeyRef
SecKeyCreate(CFAllocatorRef allocator
,
253 const SecKeyDescriptor
*key_class
, const uint8_t *keyData
,
254 CFIndex keyDataLength
, SecKeyEncoding encoding
);
256 /* Create a public key from an oid, params and keyData all in DER format. */
257 SecKeyRef
SecKeyCreatePublicFromDER(CFAllocatorRef allocator
,
258 const SecAsn1Oid
*oid1
, const SecAsn1Item
*params
,
259 const SecAsn1Item
*keyData
);
261 /* Create public key from private key */
262 SecKeyRef
SecKeyCreatePublicFromPrivate(SecKeyRef privateKey
);
264 /* Get Private Key (if present) by publicKey. */
265 SecKeyRef
SecKeyCopyMatchingPrivateKey(SecKeyRef publicKey
, CFErrorRef
*error
);
267 OSStatus
SecKeyGetMatchingPrivateKeyStatus(SecKeyRef publicKey
, CFErrorRef
*error
);
268 CFDataRef
SecKeyCreatePersistentRefToMatchingPrivateKey(SecKeyRef publicKey
, CFErrorRef
*error
);
270 /* Return an attribute dictionary used to find a private key by public key hash */
271 CFDictionaryRef
CreatePrivateKeyMatchingQuery(SecKeyRef publicKey
, bool returnPersistentRef
);
273 /* Return a key from an attribute dictionary that was used to store this item
275 SecKeyRef
SecKeyCreateFromAttributeDictionary(CFDictionaryRef refAttributes
);
277 // SecAsn1AlgId is deprecated, but we still need to use it.
278 #pragma clang diagnostic push
279 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
281 OSStatus
SecKeyDigestAndVerify(
282 SecKeyRef key
, /* Public key */
283 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
284 const uint8_t *dataToDigest
, /* signature over this data */
285 size_t dataToDigestLen
,/* length of dataToDigest */
286 const uint8_t *sig
, /* signature to verify */
287 size_t sigLen
); /* length of sig */
289 /* Return an attribute dictionary used to store this item in a keychain. */
290 CFDictionaryRef
SecKeyCopyAttributeDictionary(SecKeyRef key
);
292 OSStatus
SecKeyDigestAndSign(
293 SecKeyRef key
, /* Private key */
294 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
295 const uint8_t *dataToDigest
, /* signature over this data */
296 size_t dataToDigestLen
,/* length of dataToDigest */
297 uint8_t *sig
, /* signature, RETURNED */
298 size_t *sigLen
); /* IN/OUT */
300 OSStatus
SecKeyVerifyDigest(
301 SecKeyRef key
, /* Private key */
302 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
303 const uint8_t *digestData
, /* signature over this digest */
304 size_t digestDataLen
,/* length of dataToDigest */
305 const uint8_t *sig
, /* signature to verify */
306 size_t sigLen
); /* length of sig */
308 OSStatus
SecKeySignDigest(
309 SecKeyRef key
, /* Private key */
310 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
311 const uint8_t *digestData
, /* signature over this digest */
312 size_t digestDataLen
,/* length of digestData */
313 uint8_t *sig
, /* signature, RETURNED */
314 size_t *sigLen
); /* IN/OUT */
316 #pragma clang diagnostic pop
318 OSStatus
SecKeyCopyPublicBytes(SecKeyRef key
, CFDataRef
* serializedPublic
);
319 SecKeyRef
SecKeyCreateFromPublicBytes(CFAllocatorRef allocator
, CFIndex algorithmID
, const uint8_t *keyData
, CFIndex keyDataLength
);
320 SecKeyRef
SecKeyCreateFromPublicData(CFAllocatorRef allocator
, CFIndex algorithmID
, CFDataRef serialized
);
321 CFDataRef
SecKeyCopyPublicKeyHash(SecKeyRef key
);
323 /* This function directly creates an iOS-format SecKeyRef from public key bytes. */
324 SecKeyRef
SecKeyCreateRSAPublicKey_ios(CFAllocatorRef allocator
,
325 const uint8_t *keyData
, CFIndex keyDataLength
,
326 SecKeyEncoding encoding
);
330 CFDictionaryRef
SecKeyGeneratePrivateAttributeDictionary(SecKeyRef key
,
332 CFDataRef privateBlob
);
334 CFDictionaryRef
SecKeyGeneratePublicAttributeDictionary(SecKeyRef key
, CFTypeRef keyType
);
337 kSecNullAlgorithmID
= 0,
338 kSecRSAAlgorithmID
= 1,
339 kSecDSAAlgorithmID
= 2, /* unsupported, just here for reference. */
340 kSecECDSAAlgorithmID
= 3,
344 @function SecKeyGetAlgorithmId
345 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
346 @param key A key reference.
347 @result An algorithm identifier.
349 CFIndex
SecKeyGetAlgorithmId(SecKeyRef key
)
350 API_AVAILABLE(macos(10.8), ios(9.0));
354 @function SecKeyGetAlgorithmID
355 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
356 @param key A key reference.
357 @result An algorithm identifier.
358 @discussion Deprecated in iOS 9.0. Note that SecKeyGetAlgorithmID also exists on OS X
359 with different arguments for CDSA-based SecKeyRefs, and returns different values.
360 For compatibility, your code should migrate to use SecKeyGetAlgorithmId instead.
362 CFIndex
SecKeyGetAlgorithmID(SecKeyRef key
)
363 API_DEPRECATED_WITH_REPLACEMENT("SecKeyGetAlgorithmId", ios(5.0, 9.0)) API_UNAVAILABLE(iosmac
);
364 #endif // TARGET_OS_IPHONE
368 @function SecKeyGetAlgorithmID
369 @abstract Returns a pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure for the given key.
370 @param key A key reference.
371 @param algid On return, a pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure.
372 @result A result code. See "Security Error Codes" (SecBase.h).
373 @discussion Deprecated in OS X 10.8 and later. Continued use is strongly discouraged,
374 since there is a naming conflict with a similar function (also deprecated) on iOS that
375 had different arguments and a different return value. Use SecKeyGetAlgorithmId instead.
377 OSStatus
SecKeyGetAlgorithmID(SecKeyRef key
, const CSSM_X509_ALGORITHM_IDENTIFIER
**algid
)
378 API_DEPRECATED_WITH_REPLACEMENT("SecKeyGetAlgorithmId", macos(10.2, 10.8)) API_UNAVAILABLE(ios
);
382 typedef CF_ENUM(int, SecKeySize
) {
383 kSecKeyKeySizeInBits
= 0,
384 kSecKeySignatureSize
= 1,
385 kSecKeyEncryptedDataSize
= 2,
386 // More might belong here, but we aren't settled on how
387 // to take into account padding and/or digest types.
391 @function SecKeyGetSize
392 @abstract Returns a size in bytes.
393 @param key The key for which the block length is requested.
394 @param whichSize The size that you want evaluated.
395 @result The block length of the key in bytes.
396 @discussion If for example key is an RSA key the value returned by
397 this function is the size of the modulus.
399 size_t SecKeyGetSize(SecKeyRef key
, SecKeySize whichSize
)
400 __OSX_AVAILABLE_STARTING(__MAC_10_8
, __IPHONE_5_0
);
404 @function SecKeyLookupPersistentRef
405 @abstract Looks up a SecKeyRef via persistent ref.
406 @param persistentRef The persistent ref data for looking up.
407 @param lookedUpData retained SecKeyRef for the found object.
408 @result Errors when using SecItemFind for the persistent ref.
410 OSStatus
SecKeyFindWithPersistentRef(CFDataRef persistentRef
, SecKeyRef
* lookedUpData
)
411 __OSX_AVAILABLE_STARTING(__MAC_10_9
, __IPHONE_7_0
);
414 @function SecKeyCopyPersistentRef
415 @abstract Gets a persistent reference for a key.
416 @param key Key to make a persistent ref for.
417 @param persistentRef Allocated data representing the persistent ref.
418 @result Errors when using SecItemFind for the persistent ref.
420 OSStatus
SecKeyCopyPersistentRef(SecKeyRef key
, CFDataRef
* persistentRef
)
421 __OSX_AVAILABLE_STARTING(__MAC_10_9
, __IPHONE_7_0
);
423 extern const CFStringRef _kSecKeyWrapPGPSymAlg
; /* CFNumber */
424 extern const CFStringRef _kSecKeyWrapPGPFingerprint
; /* CFDataRef, at least 20 bytes */
425 extern const CFStringRef _kSecKeyWrapPGPWrapAlg
; /* kSecKeyWrapRFC6637WrapNNN, or any of the other PGP wrap algs */
426 extern const CFStringRef _kSecKeyWrapRFC6637Flags
;
427 extern const CFStringRef _kSecKeyWrapRFC6637WrapDigestSHA256KekAES128
;
428 extern const CFStringRef _kSecKeyWrapRFC6637WrapDigestSHA512KekAES256
;
430 enum { kSecKeyWrapPGPFingerprintMinSize
= 20 };
432 @function _SecKeyCopyWrapKey
437 _SecKeyCopyWrapKey(SecKeyRef key
, SecKeyWrapType type
, CFDataRef unwrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
)
438 __OSX_AVAILABLE_STARTING(__MAC_10_10
, __IPHONE_8_0
);
441 @function _SecKeyWrapKey
442 @abstract Unwrap a key
446 _SecKeyCopyUnwrapKey(SecKeyRef key
, SecKeyWrapType type
, CFDataRef wrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
)
447 __OSX_AVAILABLE_STARTING(__MAC_10_10
, __IPHONE_8_0
);
449 #if SEC_OS_OSX_INCLUDES
451 @function SecKeyGetStrengthInBits
452 @abstract Returns key strength in bits for the given key.
453 @param key A key reference.
454 @param algid A pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure, as returned from a call to SecKeyGetAlgorithmID.
455 @param strength On return, the key strength in bits.
456 @result A result code. See "Security Error Codes" (SecBase.h).
458 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));
461 @function SecKeyImportPair
462 @abstract Takes an asymmetric key pair and stores it in the keychain specified by the keychain parameter.
463 @param keychainRef A reference to the keychain in which to store the private and public key items. Specify NULL for the default keychain.
464 @param publicCssmKey A CSSM_KEY which is valid for the CSP returned by SecKeychainGetCSPHandle(). This may be a normal key or reference key.
465 @param privateCssmKey A CSSM_KEY which is valid for the CSP returned by SecKeychainGetCSPHandle(). This may be a normal key or reference key.
466 @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.
467 @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.
468 @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.
469 @result A result code. See "Security Error Codes" (SecBase.h).
470 @deprecated in 10.5 and later. Use the SecKeychainItemImport function instead; see <Security/SecImportExport.h>
472 OSStatus
SecKeyImportPair(
473 SecKeychainRef keychainRef
,
474 const CSSM_KEY
*publicCssmKey
,
475 const CSSM_KEY
*privateCssmKey
,
476 SecAccessRef initialAccess
,
477 SecKeyRef
* publicKey
,
478 SecKeyRef
* privateKey
)
479 DEPRECATED_IN_MAC_OS_X_VERSION_10_5_AND_LATER
;
482 @function SecKeyCreate
483 @abstract Create a key reference from the supplied key data.
484 @param allocator CFAllocator to allocate the key data. Pass NULL to use the default allocator.
485 @param keyClass A descriptor for the particular class of key that is being created.
486 @param keyData Data from which to create the key. Specify the format of this data in the encoding parameter.
487 @param keyDataLength Length of the data pointed to by keyData.
488 @param encoding A value of type SecKeyEncoding which describes the format of keyData.
489 @result A key reference.
490 @discussion Warning: this function is NOT intended for use outside the Security stack in its current state. <rdar://3201885>
491 IMPORTANT: on Mac OS X 10.5 and earlier, the SecKeyCreate function had a different parameter list.
492 The current parameter list matches the iPhone OS implementation. Existing clients of this function
493 on Mac OS X (and there should not be any outside the Security stack, per the warning above) must
494 migrate to the replacement function, SecKeyCreateWithCSSMKey.
496 SecKeyRef
SecKeyCreate(CFAllocatorRef allocator
,
497 const SecKeyDescriptor
*keyClass
, const uint8_t *keyData
,
498 CFIndex keyDataLength
, SecKeyEncoding encoding
);
501 @function SecKeyCreateWithCSSMKey
502 @abstract Generate a temporary floating key reference for a CSSM_KEY.
503 @param key A pointer to a CSSM_KEY structure.
504 @param keyRef On return, a key reference.
505 @result A result code. See "Security Error Codes" (SecBase.h).
506 @discussion Warning: this function is NOT intended for use outside the Security stack in its current state. <rdar://3201885>
508 OSStatus
SecKeyCreateWithCSSMKey(const CSSM_KEY
*key
, SecKeyRef
* keyRef
) API_DEPRECATED("CSSM_KEY is deprecated", macos(10.11, 10.14));
512 @function SecKeyRawSign
513 @abstract Given a private key and data to sign, generate a digital signature.
514 @param key Private key with which to sign.
515 @param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
516 @param dataToSign The data to be signed, typically the digest of the actual data.
517 @param dataToSignLen Length of dataToSign in bytes.
518 @param sig Pointer to buffer in which the signature will be returned.
519 @param sigLen IN/OUT maximum length of sig buffer on input, actualy length of sig on output.
520 @result A result code. See "Security Error Codes" (SecBase.h).
521 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
522 will be performed prior to signing. If this argument is kSecPaddingNone,
523 the incoming data will be signed "as is".
525 When PKCS1 padding is performed, the maximum length of data that can
526 be signed is the value returned by SecKeyGetBlockSize() - 11.
528 NOTE: The behavior this function with kSecPaddingNone is undefined if the
529 first byte of dataToSign is zero; there is no way to verify leading zeroes
530 as they are discarded during the calculation.
532 If you want to generate a proper PKCS1 style signature with DER encoding of
533 the digest type - and the dataToSign is a SHA1 digest - use kSecPaddingPKCS1SHA1.
535 OSStatus
SecKeyRawSign(
538 const uint8_t *dataToSign
,
539 size_t dataToSignLen
,
545 @function SecKeyRawVerify
546 @abstract Given a public key, data which has been signed, and a signature, verify the signature.
547 @param key Public key with which to verify the signature.
548 @param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
549 @param signedData The data over which sig is being verified, typically the digest of the actual data.
550 @param signedDataLen Length of signedData in bytes.
551 @param sig Pointer to the signature to verify.
552 @param sigLen Length of sig in bytes.
553 @result A result code. See "Security Error Codes" (SecBase.h).
554 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
555 will be checked during verification. If this argument is kSecPaddingNone,
556 the incoming data will be compared directly to sig.
558 If you are verifying a proper PKCS1-style signature, with DER encoding of the digest
559 type - and the signedData is a SHA1 digest - use kSecPaddingPKCS1SHA1.
561 OSStatus
SecKeyRawVerify(
564 const uint8_t *signedData
,
565 size_t signedDataLen
,
571 @function SecKeyEncrypt
572 @abstract Encrypt a block of plaintext.
573 @param key Public key with which to encrypt the data.
574 @param padding See Padding Types above, typically kSecPaddingPKCS1.
575 @param plainText The data to encrypt.
576 @param plainTextLen Length of plainText in bytes, this must be less
577 or equal to the value returned by SecKeyGetBlockSize().
578 @param cipherText Pointer to the output buffer.
579 @param cipherTextLen On input, specifies how much space is available at
580 cipherText; on return, it is the actual number of cipherText bytes written.
581 @result A result code. See "Security Error Codes" (SecBase.h).
582 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
583 will be performed prior to encryption. If this argument is kSecPaddingNone,
584 the incoming data will be encrypted "as is".
586 When PKCS1 padding is performed, the maximum length of data that can
587 be encrypted is the value returned by SecKeyGetBlockSize() - 11.
589 When memory usage is a critical issue, note that the input buffer
590 (plainText) can be the same as the output buffer (cipherText).
592 OSStatus
SecKeyEncrypt(
595 const uint8_t *plainText
,
598 size_t *cipherTextLen
);
602 @function SecKeyDecrypt
603 @abstract Decrypt a block of ciphertext.
604 @param key Private key with which to decrypt the data.
605 @param padding See SecPadding types above; typically kSecPaddingPKCS1.
606 @param cipherText The data to decrypt.
607 @param cipherTextLen Length of cipherText in bytes; this must be less
608 or equal to the value returned by SecKeyGetBlockSize().
609 @param plainText Pointer to the output buffer.
610 @param plainTextLen On input, specifies how much space is available at
611 plainText; on return, it is the actual number of plainText bytes written.
612 @result A result code. See "Security Error Codes" (SecBase.h).
613 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
614 will be removed after decryption. If this argument is kSecPaddingNone,
615 the decrypted data will be returned "as is".
617 When memory usage is a critical issue, note that the input buffer
618 (plainText) can be the same as the output buffer (cipherText).
620 OSStatus
SecKeyDecrypt(
621 SecKeyRef key
, /* Private key */
622 SecPadding padding
, /* kSecPaddingNone, kSecPaddingPKCS1, kSecPaddingOAEP */
623 const uint8_t *cipherText
,
624 size_t cipherTextLen
, /* length of cipherText */
626 size_t *plainTextLen
); /* IN/OUT */
628 // SecAsn1AlgId is deprecated, but we still need to use it.
629 #pragma clang diagnostic push
630 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
631 OSStatus
SecKeyVerifyDigest(
632 SecKeyRef key
, /* Private key */
633 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
634 const uint8_t *digestData
, /* signature over this digest */
635 size_t digestDataLen
, /* length of dataToDigest */
636 const uint8_t *sig
, /* signature to verify */
637 size_t sigLen
); /* length of sig */
639 OSStatus
SecKeySignDigest(
640 SecKeyRef key
, /* Private key */
641 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
642 const uint8_t *digestData
, /* signature over this digest */
643 size_t digestDataLen
, /* length of digestData */
644 uint8_t *sig
, /* signature, RETURNED */
645 size_t *sigLen
); /* IN/OUT */
646 #pragma clang diagnostic pop
648 #endif // SEC_OS_OSX_INCLUDES
651 /* These are the named curves we support. These values come from RFC 4492
652 section 5.1.1, with the exception of SSL_Curve_None which means
653 "ECDSA not negotiated". */
656 kSecECCurveNone
= -1,
657 kSecECCurveSecp256r1
= 23,
658 kSecECCurveSecp384r1
= 24,
659 kSecECCurveSecp521r1
= 25
662 /* Return a named curve enum for ecPrivateKey. */
663 SecECNamedCurve
SecECKeyGetNamedCurve(SecKeyRef ecPrivateKey
);
664 CFDataRef
SecECKeyCopyPublicBits(SecKeyRef key
);
666 /* Given an RSA public key in encoded form return a SecKeyRef representing
667 that key. Supported encodings are kSecKeyEncodingPkcs1. */
668 SecKeyRef
SecKeyCreateRSAPublicKey(CFAllocatorRef allocator
,
669 const uint8_t *keyData
, CFIndex keyDataLength
,
670 SecKeyEncoding encoding
);
672 CFDataRef
SecKeyCopyModulus(SecKeyRef rsaPublicKey
);
673 CFDataRef
SecKeyCopyExponent(SecKeyRef rsaPublicKey
);
676 @function SecKeyCopyPublicBytes
677 @abstract Gets the bits of a public key
678 @param key Key to retrieve the bits.
679 @param publicBytes An out parameter to receive the public key bits
680 @result Errors if any when retrieving the public key bits..
682 OSStatus
SecKeyCopyPublicBytes(SecKeyRef key
, CFDataRef
* publicBytes
);
685 @function SecKeyCreatePublicFromPrivate
686 @abstract Create a public SecKeyRef from a private SecKeyRef
687 @param privateKey The private SecKeyRef for which you want the public key
688 @result A public SecKeyRef, or NULL if the conversion failed
689 @discussion This is a "best attempt" function, hence the SPI nature. If the public
690 key bits are not in memory, it attempts to load from the keychain. If the public
691 key was not tracked on the keychain, it will fail.
693 SecKeyRef
SecKeyCreatePublicFromPrivate(SecKeyRef privateKey
);
696 @function SecKeyCreateFromPublicData
698 SecKeyRef
SecKeyCreateFromPublicData(CFAllocatorRef allocator
, CFIndex algorithmID
, CFDataRef publicBytes
);
700 #if SEC_OS_OSX_INCLUDES
701 OSStatus
SecKeyRawVerifyOSX(
704 const uint8_t *signedData
,
705 size_t signedDataLen
,
709 #endif // SEC_OS_OSX_INCLUDES
712 @enum SecKeyAttestationKeyType
713 @abstract Defines types of builtin attestation keys.
715 typedef CF_ENUM(uint32_t, SecKeyAttestationKeyType
)
717 kSecKeyAttestationKeyTypeSIK
= 0,
718 kSecKeyAttestationKeyTypeGID
= 1,
719 kSecKeyAttestationKeyTypeUIKCommitted
API_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0)) = 2,
720 kSecKeyAttestationKeyTypeUIKProposed
API_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0)) = 3,
721 } API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
724 @function SecKeyCopyAttestationKey
725 @abstract Returns a copy of a builtin attestation key.
727 @param keyType Type of the requested builtin key.
728 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
730 @result On success a SecKeyRef containing the requested key is returned, on failure it returns NULL.
732 SecKeyRef
SecKeyCopyAttestationKey(SecKeyAttestationKeyType keyType
, CFErrorRef
*error
)
733 API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
736 @function SecKeyCreateAttestation
737 @abstract Attests a key with another key.
739 @param key The attesting key.
740 @param keyToAttest The key which is to be attested.
741 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
743 @result On success a CFDataRef containing the attestation data is returned, on failure it returns NULL.
745 @discussion Key attestation only works for CTK SEP keys, i.e. keys created with kSecAttrTokenID=kSecAttrTokenIDSecureEnclave.
747 CFDataRef
SecKeyCreateAttestation(SecKeyRef key
, SecKeyRef keyToAttest
, CFErrorRef
*error
)
748 API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
751 @function SecKeySetParameter
752 @abstract Sets unspecified key parameter for the backend.
754 @param key Key to set the parameter to.
755 @param name Identifies parameter to be set.
756 @param value New value for the parameter.
757 @param error Error which gathers more information when something went wrong.
759 @discussion Serves as channel between SecKey client and backend for passing additional sideband data send from SecKey caller
760 to SecKey implementation backend. Parameter names and types are either generic kSecUse*** attributes or are a contract between
761 SecKey user (application) and backend and in this case are not interpreted by SecKey layer in any way.
763 Boolean
SecKeySetParameter(SecKeyRef key
, CFStringRef name
, CFPropertyListRef value
, CFErrorRef
*error
)
764 API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
766 extern const CFStringRef kSecKeyParameterSETokenAttestationNonce
767 API_AVAILABLE(macos(10.13), ios(11.0), tvos(11.0), watchos(4.0));
770 Available lifetime operations for SEP system keys.
772 typedef CF_ENUM(int, SecKeyControlLifetimeType
) {
773 kSecKeyControlLifetimeTypeBump
= 0,
774 kSecKeyControlLifetimeTypeCommit
= 1,
775 } API_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0));
778 @function SecKeyControlLifetime
779 @abstract Performs key lifetime control operations for SEP system keys.
781 @param key Key to be controlled, currently must be either proposed or committed system UIK.
782 @param type Type of the control operation to be performed.
783 @param error Error which gathers more information when something went wrong.
785 Boolean
SecKeyControlLifetime(SecKeyRef key
, SecKeyControlLifetimeType type
, CFErrorRef
*error
)
786 API_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0));
789 @function SecKeyCreateDuplicate
790 @abstract Creates duplicate fo the key.
792 @param key Source key to be duplicated
794 @discussion Only memory representation of the key is duplicated, so if the key is backed by keychain, only one instance
795 stays in the keychain. Duplicating key is useful for setting 'temporary' key parameters using SecKeySetParameter.
796 If the key is immutable (i.e. does not support SecKeySetParameter), calling this method is identical to calling CFRetain().
798 SecKeyRef
SecKeyCreateDuplicate(SecKeyRef key
)
799 API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0));
802 Algorithms for converting between bigendian and core-crypto ccunit data representation.
804 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureRawCCUnit
;
805 extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionRawCCUnit
;
808 Internal algorithm for RSA-MD5. We do not want to export MD5 in new API, but we need it
809 for implementing legacy interfaces.
811 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15MD5
;
812 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15MD5
;
815 Algorithms for interoperability with libaks smartcard support.
817 extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionAKSSmartCard
;
821 #endif /* !_SECURITY_SECKEYPRIV_H_ */