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/SecKey.h>
37 #include <Security/SecAsn1Types.h>
38 #include <CoreFoundation/CFRuntime.h>
39 #include <CoreFoundation/CoreFoundation.h>
40 #include <CoreFoundation/CFDictionary.h>
44 typedef struct __SecDERKey
{
49 CFIndex parametersLength
;
51 /* Contents of BIT STRING in DER Encoding */
57 typedef uint32_t SecKeyEncoding
;
59 /* Typically only used for symmetric keys. */
60 kSecKeyEncodingRaw
= 0,
62 /* RSA keys are DER-encoded according to PKCS1. */
63 kSecKeyEncodingPkcs1
= 1,
65 /* RSA keys are DER-encoded according to PKCS1 with Apple Extensions. */
66 kSecKeyEncodingApplePkcs1
= 2,
68 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
69 to a SecRSAPublicKeyParams and keyDataLength is
70 sizeof(SecRSAPublicKeyParams). */
71 kSecKeyEncodingRSAPublicParams
= 3,
73 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
74 to a SecRSAPublicKeyParams and keyDataLength is
75 sizeof(SecRSAPublicKeyParams). */
76 kSecDERKeyEncoding
= 4,
78 /* Internal "encodings to send other data" */
80 kSecExtractPublicFromPrivate
= 6,
82 /* Encoding came from SecKeyCopyPublicBytes for a public key,
83 or internally from a private key */
84 kSecKeyEncodingBytes
= 7,
86 /* Handing in a private key from corecrypto directly. */
87 kSecKeyCoreCrypto
= 8,
91 typedef uint32_t SecKeyWrapType
;
93 /* wrap key in RFC3394 (AESWrap) */
94 kSecKeyWrapRFC3394
= 0,
96 /* wrap key in PGP style (support EC keys only right now) */
97 kSecKeyWrapPublicKeyPGP
= 1,
101 typedef CF_ENUM(CFIndex
, SecKeyOperationMode
) {
102 kSecKeyOperationModePerform
= 0,
103 kSecKeyOperationModeCheckIfSupported
= 1,
106 typedef OSStatus (*SecKeyInitMethod
)(SecKeyRef
, const uint8_t *, CFIndex
,
108 typedef void (*SecKeyDestroyMethod
)(SecKeyRef
);
109 typedef OSStatus (*SecKeyRawSignMethod
)(SecKeyRef key
, SecPadding padding
,
110 const uint8_t *dataToSign
, size_t dataToSignLen
,
111 uint8_t *sig
, size_t *sigLen
);
112 typedef OSStatus (*SecKeyRawVerifyMethod
)(
113 SecKeyRef key
, SecPadding padding
, const uint8_t *signedData
,
114 size_t signedDataLen
, const uint8_t *sig
, size_t sigLen
);
115 typedef OSStatus (*SecKeyEncryptMethod
)(SecKeyRef key
, SecPadding padding
,
116 const uint8_t *plainText
, size_t plainTextLen
,
117 uint8_t *cipherText
, size_t *cipherTextLen
);
118 typedef OSStatus (*SecKeyDecryptMethod
)(SecKeyRef key
, SecPadding padding
,
119 const uint8_t *cipherText
, size_t cipherTextLen
,
120 uint8_t *plainText
, size_t *plainTextLen
);
121 typedef OSStatus (*SecKeyComputeMethod
)(SecKeyRef key
,
122 const uint8_t *pub_key
, size_t pub_key_len
,
123 uint8_t *computed_key
, size_t *computed_key_len
);
124 typedef size_t (*SecKeyBlockSizeMethod
)(SecKeyRef key
);
125 typedef CFDictionaryRef (*SecKeyCopyDictionaryMethod
)(SecKeyRef key
);
126 typedef CFIndex (*SecKeyGetAlgorithmIDMethod
)(SecKeyRef key
);
127 typedef OSStatus (*SecKeyCopyPublicBytesMethod
)(SecKeyRef key
, CFDataRef
*serialization
);
128 typedef CFDataRef (*SecKeyCopyWrapKeyMethod
)(SecKeyRef key
, SecKeyWrapType type
, CFDataRef unwrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
);
129 typedef CFDataRef (*SecKeyCopyUnwrapKeyMethod
)(SecKeyRef key
, SecKeyWrapType type
, CFDataRef wrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
);
130 typedef CFStringRef (*SecKeyDescribeMethod
)(SecKeyRef key
);
132 typedef CFDataRef (*SecKeyCopyExternalRepresentationMethod
)(SecKeyRef key
, CFErrorRef
*error
);
133 typedef SecKeyRef (*SecKeyCopyPublicKeyMethod
)(SecKeyRef key
);
134 typedef Boolean (*SecKeyIsEqualMethod
)(SecKeyRef key1
, SecKeyRef key2
);
135 typedef SecKeyRef (*SecKeyCreateDuplicateMethod
)(SecKeyRef key
);
136 typedef Boolean (*SecKeySetParameterMethod
)(SecKeyRef key
, CFStringRef name
, CFPropertyListRef value
, CFErrorRef
*error
);
139 @abstract Performs cryptographic operation with the key.
140 @param key Key to perform the operation on.
141 @param operation Type of operation to be performed.
142 @param algorithm Algorithm identifier for the operation. Determines format of input and output data.
143 @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.
144 @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.
145 @param in1 First input parameter for the operation, meaningful only in ModePerform.
146 @param in2 Second input parameter for the operation, meaningful only in ModePerform.
147 @param error Error details when NULL is returned.
148 @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.
150 typedef CFTypeRef(*SecKeyCopyOperationResultMethod
)(SecKeyRef key
, SecKeyOperationType operation
, SecKeyAlgorithm algorithm
, CFArrayRef allAlgorithms
, SecKeyOperationMode mode
, CFTypeRef in1
, CFTypeRef in2
, CFErrorRef
*error
);
152 #define kSecKeyDescriptorVersion (4)
154 typedef struct __SecKeyDescriptor
{
155 /* Version of this SecKeyDescriptor. Must be kSecKeyDescriptorVersion. */
158 /* Name of this key class for use by SecKeyShow(). */
161 /* If nonzero, SecKeyCreate will allocate this many bytes for the key
162 field in the SecKeyRef it creates. If zero key is NULL and the
163 implementor can choose to dynamically allocate it in the init
164 function and free it in the destroy function. */
167 /* Called by SecKeyCreate(). */
168 SecKeyInitMethod init
;
169 /* Called by destructor (final CFRelease() or gc if using). */
170 SecKeyDestroyMethod destroy
;
171 /* Called by SecKeyRawSign(). */
172 SecKeyRawSignMethod rawSign
;
173 /* Called by SecKeyRawVerify(). */
174 SecKeyRawVerifyMethod rawVerify
;
175 /* Called by SecKeyEncrypt(). */
176 SecKeyEncryptMethod encrypt
;
177 /* Called by SecKeyDecrypt(). */
178 SecKeyDecryptMethod decrypt
;
179 /* Reserved for future use. */
180 SecKeyComputeMethod compute
;
181 /* Called by SecKeyGetBlockSize(). */
182 SecKeyBlockSizeMethod blockSize
;
183 /* Called by SecKeyCopyAttributeDictionary(), which is private. */
184 SecKeyCopyDictionaryMethod copyDictionary
;
185 /* Called by SecKeyDescribeMethod(). */
186 SecKeyDescribeMethod describe
;
187 #if kSecKeyDescriptorVersion > 0
188 /* Called by SecKeyCopyAttributeDictionary(), which is private. */
189 SecKeyGetAlgorithmIDMethod getAlgorithmID
;
191 #if kSecKeyDescriptorVersion > 1
192 SecKeyCopyPublicBytesMethod copyPublic
;
194 #if kSecKeyDescriptorVersion > 2
195 SecKeyCopyWrapKeyMethod copyWrapKey
;
196 SecKeyCopyUnwrapKeyMethod copyUnwrapKey
;
198 #if kSecKeyDescriptorVersion > 3
199 SecKeyCopyExternalRepresentationMethod copyExternalRepresentation
;
200 SecKeyCopyPublicKeyMethod copyPublicKey
;
201 SecKeyCopyOperationResultMethod copyOperationResult
;
202 SecKeyIsEqualMethod isEqual
;
203 SecKeyCreateDuplicateMethod createDuplicate
;
204 SecKeySetParameterMethod setParameter
;
211 const SecKeyDescriptor
*key_class
;
213 #if !TARGET_OS_IPHONE
214 // On OSX, keep optional SecKeyRef which holds dynamically, on-demand created CSSM-based key with the same
215 // key material. It is used to implement SecKeyGetCSSMKey().
219 /* The actual key handled by class. */
224 @function SecKeyCreate
225 @abstract Given a private key and data to sign, generate a digital signature.
226 @param allocator allocator to use when allocating this key instance.
227 @param key_class pointer to a SecKeyDescriptor.
228 @param keyData The second argument to the init() function in the key_class.
229 @param keyDataLength The third argument to the init() function in the key_class.
230 @param encoding The fourth argument to the init() function in the key_class.
231 @result A newly allocated SecKeyRef.
233 SecKeyRef
SecKeyCreate(CFAllocatorRef allocator
,
234 const SecKeyDescriptor
*key_class
, const uint8_t *keyData
,
235 CFIndex keyDataLength
, SecKeyEncoding encoding
);
237 /* Create a public key from an oid, params and keyData all in DER format. */
238 SecKeyRef
SecKeyCreatePublicFromDER(CFAllocatorRef allocator
,
239 const SecAsn1Oid
*oid1
, const SecAsn1Item
*params
,
240 const SecAsn1Item
*keyData
);
242 /* Create a public key from a CFData containing a SubjectPublicKeyInfo in DER format. */
243 SecKeyRef
SecKeyCreateFromSubjectPublicKeyInfoData(CFAllocatorRef allocator
,
244 CFDataRef subjectPublicKeyInfoData
);
246 /* Create public key from private key */
247 SecKeyRef
SecKeyCreatePublicFromPrivate(SecKeyRef privateKey
);
249 /* Get Private Key (if present) by publicKey. */
250 SecKeyRef
SecKeyCopyMatchingPrivateKey(SecKeyRef publicKey
, CFErrorRef
*error
);
251 OSStatus
SecKeyGetMatchingPrivateKeyStatus(SecKeyRef publicKey
, CFErrorRef
*error
);
253 CFDataRef
SecKeyCreatePersistentRefToMatchingPrivateKey(SecKeyRef publicKey
, CFErrorRef
*error
);
255 /* Return an attribute dictionary used to find a private key by public key hash */
256 CFDictionaryRef
CreatePrivateKeyMatchingQuery(SecKeyRef publicKey
, bool returnPersistentRef
);
258 /* Return an attribute dictionary used to store this item in a keychain. */
259 CFDictionaryRef
SecKeyCopyAttributeDictionary(SecKeyRef key
);
261 /* Return a key from an attribute dictionary that was used to store this item
263 SecKeyRef
SecKeyCreateFromAttributeDictionary(CFDictionaryRef refAttributes
);
265 OSStatus
SecKeyDigestAndVerify(
266 SecKeyRef key
, /* Public key */
267 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
268 const uint8_t *dataToDigest
, /* signature over this data */
269 size_t dataToDigestLen
,/* length of dataToDigest */
270 const uint8_t *sig
, /* signature to verify */
271 size_t sigLen
); /* length of sig */
273 OSStatus
SecKeyDigestAndSign(
274 SecKeyRef key
, /* Private key */
275 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
276 const uint8_t *dataToDigest
, /* signature over this data */
277 size_t dataToDigestLen
,/* length of dataToDigest */
278 uint8_t *sig
, /* signature, RETURNED */
279 size_t *sigLen
); /* IN/OUT */
281 OSStatus
SecKeyVerifyDigest(
282 SecKeyRef key
, /* Private key */
283 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
284 const uint8_t *digestData
, /* signature over this digest */
285 size_t digestDataLen
,/* length of dataToDigest */
286 const uint8_t *sig
, /* signature to verify */
287 size_t sigLen
); /* length of sig */
289 OSStatus
SecKeySignDigest(
290 SecKeyRef key
, /* Private key */
291 const SecAsn1AlgId
*algId
, /* algorithm oid/params */
292 const uint8_t *digestData
, /* signature over this digest */
293 size_t digestDataLen
,/* length of digestData */
294 uint8_t *sig
, /* signature, RETURNED */
295 size_t *sigLen
); /* IN/OUT */
297 OSStatus
SecKeyCopyPublicBytes(SecKeyRef key
, CFDataRef
* serializedPublic
);
298 SecKeyRef
SecKeyCreateFromPublicBytes(CFAllocatorRef allocator
, CFIndex algorithmID
, const uint8_t *keyData
, CFIndex keyDataLength
);
299 SecKeyRef
SecKeyCreateFromPublicData(CFAllocatorRef allocator
, CFIndex algorithmID
, CFDataRef serialized
);
300 CFDataRef
SecKeyCopyPublicKeyHash(SecKeyRef key
);
302 /* This function directly creates an iOS-format SecKeyRef from public key bytes. */
303 SecKeyRef
SecKeyCreateRSAPublicKey_ios(CFAllocatorRef allocator
,
304 const uint8_t *keyData
, CFIndex keyDataLength
,
305 SecKeyEncoding encoding
);
309 CFDictionaryRef
SecKeyGeneratePrivateAttributeDictionary(SecKeyRef key
,
311 CFDataRef privateBlob
);
313 CFDictionaryRef
SecKeyGeneratePublicAttributeDictionary(SecKeyRef key
, CFTypeRef keyType
);
316 kSecNullAlgorithmID
= 0,
317 kSecRSAAlgorithmID
= 1,
318 kSecDSAAlgorithmID
= 2, /* unsupported, just here for reference. */
319 kSecECDSAAlgorithmID
= 3,
323 @function SecKeyGetAlgorithmID
324 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
325 @param key A key reference.
326 @result An algorithm identifier.
327 @discussion Deprecated in iOS 9.0. Note that SecKeyGetAlgorithmID also exists on OS X
328 with different arguments for CDSA-based SecKeyRefs, and returns different values.
329 For compatibility, your code should migrate to use SecKeyGetAlgorithmId instead.
331 CFIndex
SecKeyGetAlgorithmID(SecKeyRef key
)
332 __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_2
, __MAC_10_8
, __IPHONE_5_0
, __IPHONE_9_0
);
335 @function SecKeyGetAlgorithmId
336 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
337 @param key A key reference.
338 @result An algorithm identifier.
340 CFIndex
SecKeyGetAlgorithmId(SecKeyRef key
)
341 __OSX_AVAILABLE_STARTING(__MAC_10_8
, __IPHONE_9_0
);
345 kSecKeyKeySizeInBits
= 0,
346 kSecKeySignatureSize
= 1,
347 kSecKeyEncryptedDataSize
= 2,
348 // More might belong here, but we aren't settled on how
349 // to take into account padding and/or digest types.
353 @function SecKeyGetSize
354 @abstract Returns a size in bytes.
355 @param key The key for which the block length is requested.
356 @param whichSize The size that you want evaluated.
357 @result The block length of the key in bytes.
358 @discussion If for example key is an RSA key the value returned by
359 this function is the size of the modulus.
361 size_t SecKeyGetSize(SecKeyRef key
, SecKeySize whichSize
)
362 __OSX_AVAILABLE_STARTING(__MAC_10_8
, __IPHONE_5_0
);
366 @function SecKeyLookupPersistentRef
367 @abstract Looks up a SecKeyRef via persistent ref.
368 @param persistentRef The persistent ref data for looking up.
369 @param lookedUpData retained SecKeyRef for the found object.
370 @result Errors when using SecItemFind for the persistent ref.
372 OSStatus
SecKeyFindWithPersistentRef(CFDataRef persistentRef
, SecKeyRef
* lookedUpData
)
373 __OSX_AVAILABLE_STARTING(__MAC_10_9
, __IPHONE_7_0
);
376 @function SecKeyCopyPersistentRef
377 @abstract Gets a persistent reference for a key.
378 @param key Key to make a persistent ref for.
379 @param persistentRef Allocated data representing the persistent ref.
380 @result Errors when using SecItemFind for the persistent ref.
382 OSStatus
SecKeyCopyPersistentRef(SecKeyRef key
, CFDataRef
* persistentRef
)
383 __OSX_AVAILABLE_STARTING(__MAC_10_9
, __IPHONE_7_0
);
390 extern const CFStringRef _kSecKeyWrapPGPSymAlg
; /* CFNumber */
391 extern const CFStringRef _kSecKeyWrapPGPFingerprint
; /* CFDataRef, at least 20 bytes */
392 extern const CFStringRef _kSecKeyWrapPGPWrapAlg
; /* kSecKeyWrapRFC6637WrapNNN, or any of the other PGP wrap algs */
393 extern const CFStringRef _kSecKeyWrapRFC6637Flags
;
394 extern const CFStringRef _kSecKeyWrapRFC6637WrapDigestSHA256KekAES128
;
395 extern const CFStringRef _kSecKeyWrapRFC6637WrapDigestSHA512KekAES256
;
397 enum { kSecKeyWrapPGPFingerprintMinSize
= 20 };
399 @function _SecKeyCopyWrapKey
404 _SecKeyCopyWrapKey(SecKeyRef key
, SecKeyWrapType type
, CFDataRef unwrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
)
405 __OSX_AVAILABLE_STARTING(__MAC_10_10
, __IPHONE_8_0
);
408 @function _SecKeyWrapKey
409 @abstract Unwrap a key
413 _SecKeyCopyUnwrapKey(SecKeyRef key
, SecKeyWrapType type
, CFDataRef wrappedKey
, CFDictionaryRef parameters
, CFDictionaryRef
*outParam
, CFErrorRef
*error
)
414 __OSX_AVAILABLE_STARTING(__MAC_10_10
, __IPHONE_8_0
);
417 @enum SecKeyAttestationKeyType
418 @abstract Defines types of builtin attestation keys.
420 typedef CF_ENUM(uint32_t, SecKeyAttestationKeyType
)
422 kSecKeyAttestationKeyTypeSIK
= 0,
423 kSecKeyAttestationKeyTypeGID
424 } __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
427 @function SecKeyCopyAttestationKey
428 @abstract Returns a copy of a builtin attestation key.
430 @param keyType Type of the requested builtin key.
431 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
433 @result On success a SecKeyRef containing the requested key is returned, on failure it returns NULL.
435 SecKeyRef
SecKeyCopyAttestationKey(SecKeyAttestationKeyType keyType
, CFErrorRef
*error
)
436 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
439 @function SecKeyCreateAttestation
440 @abstract Attests a key with another key.
442 @param key The attesting key.
443 @param keyToAttest The key which is to be attested.
444 @param error An optional pointer to a CFErrorRef. This value is set if an error occurred.
446 @result On success a CFDataRef containing the attestation data is returned, on failure it returns NULL.
448 @discussion Key attestation only works for CTK SEP keys, i.e. keys created with kSecAttrTokenID=kSecAttrTokenIDSecureEnclave.
450 CFDataRef
SecKeyCreateAttestation(SecKeyRef key
, SecKeyRef keyToAttest
, CFErrorRef
*error
)
451 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
454 @function SecKeySetParameter
455 @abstract Sets unspecified key parameter for the backend.
457 @param key Key to set the parameter to.
458 @param name Identifies parameter to be set.
459 @param value New value for the parameter.
460 @param error Error which gathers more information when something went wrong.
462 @discussion Serves as channel between SecKey client and backend for passing additional sideband data send from SecKey caller
463 to SecKey implementation backend. Parameter names and types are either generic kSecUse*** attributes or are a contract between
464 SecKey user (application) and backend and in this case are not interpreted by SecKey layer in any way.
466 Boolean
SecKeySetParameter(SecKeyRef key
, CFStringRef name
, CFPropertyListRef value
, CFErrorRef
*error
)
467 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
470 @function SecKeyCreateDuplicate
471 @abstract Creates duplicate fo the key.
473 @param key Source key to be duplicated
475 @discussion Only memory representation of the key is duplicated, so if the key is backed by keychain, only one instance
476 stays in the keychain. Duplicating key is useful for setting 'temporary' key parameters using SecKeySetParameter.
477 If the key is immutable (i.e. does not support SecKeySetParameter), calling this method is identical to calling CFRetain().
479 SecKeyRef
SecKeyCreateDuplicate(SecKeyRef key
)
480 __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
483 Algorithms for converting between bigendian and core-crypto ccunit data representation.
485 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureRawCCUnit
;
486 extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionRawCCUnit
;
489 Internal algorithm for RSA-MD5. We do not want to export MD5 in new API, but we need it
490 for implementing legacy interfaces.
492 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15MD5
;
493 extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15MD5
;
496 Algorithms for interoperability with libaks smartcard support.
498 extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionAKSSmartCard
;
502 #endif /* !_SECURITY_SECKEYPRIV_H_ */