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