]> git.saurik.com Git - apple/security.git/blob - libsecurity_keychain/lib/SecKeyPriv.h
Security-55179.13.tar.gz
[apple/security.git] / libsecurity_keychain / lib / SecKeyPriv.h
1 /*
2 * Copyright (c) 2002-2009 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 * SecKeyPriv.h - SPIs to SecKeyRef objects.
24 */
25
26 /*!
27 @header SecKeyPriv
28 The functions provided in SecKeyPriv.h implement and manage a particular
29 type of keychain item that represents a key. A key can be stored in a
30 keychain, but a key can also be a transient object.
31
32 You can use a key as a keychain item in most functions.
33 */
34
35 #ifndef _SECURITY_SECKEYPRIV_H_
36 #define _SECURITY_SECKEYPRIV_H_
37
38 #include <Security/SecKey.h>
39 #include <Security/x509defs.h>
40 #include <Security/SecAsn1Types.h>
41 #include <AvailabilityMacros.h>
42
43 #if defined(__cplusplus)
44 extern "C" {
45 #endif
46
47 typedef uint32_t SecKeyEncoding;
48 enum {
49 /* Typically only used for symmetric keys. */
50 kSecKeyEncodingRaw = 0,
51
52 /* RSA keys are DER-encoded according to PKCS1. */
53 kSecKeyEncodingPkcs1 = 1,
54
55 /* RSA keys are DER-encoded according to PKCS1 with Apple Extensions. */
56 kSecKeyEncodingApplePkcs1 = 2,
57
58 /* RSA public key in SecRSAPublicKeyParams format. keyData is a pointer
59 to a SecRSAPublicKeyParams and keyDataLength is
60 sizeof(SecRSAPublicKeyParams). */
61 kSecKeyEncodingRSAPublicParams = 3,
62 };
63
64 typedef OSStatus (*SecKeyInitMethod)(SecKeyRef, const uint8_t *, CFIndex,
65 SecKeyEncoding);
66 typedef void *(*SecKeyCopyMethod)(SecKeyRef);
67 typedef void (*SecKeyDestroyMethod)(SecKeyRef);
68 typedef void (*SecKeyDeleteMethod)(SecKeyRef);
69 typedef void (*SecKeyShowMethod)(SecKeyRef);
70 typedef OSStatus (*SecKeyRawSignMethod)(SecKeyRef key, SecPadding padding,
71 const uint8_t *dataToSign, size_t dataToSignLen,
72 uint8_t *sig, size_t *sigLen);
73 typedef OSStatus (*SecKeyRawVerifyMethod)(
74 SecKeyRef key, SecPadding padding, const uint8_t *signedData,
75 size_t signedDataLen, const uint8_t *sig, size_t sigLen);
76 typedef OSStatus (*SecKeyEncryptMethod)(SecKeyRef key, SecPadding padding,
77 const uint8_t *plainText, size_t plainTextLen,
78 uint8_t *cipherText, size_t *cipherTextLen);
79 typedef OSStatus (*SecKeyDecryptMethod)(SecKeyRef key, SecPadding padding,
80 const uint8_t *cipherText, size_t cipherTextLen,
81 uint8_t *plainText, size_t *plainTextLen);
82 typedef size_t (*SecKeyBlockSizeMethod)(SecKeyRef key);
83 typedef CFDictionaryRef (*SecKeyCopyDictionaryMethod)(SecKeyRef key);
84
85 typedef struct {
86 const char *name;
87 SecKeyInitMethod init;
88 SecKeyCopyMethod copy;
89 SecKeyDestroyMethod destroy;
90 SecKeyDeleteMethod remove;
91 SecKeyShowMethod show;
92 SecKeyRawSignMethod rawSign;
93 SecKeyRawVerifyMethod rawVerify;
94 SecKeyEncryptMethod encrypt;
95 SecKeyDecryptMethod decrypt;
96 SecKeyBlockSizeMethod blockSize;
97 SecKeyCopyDictionaryMethod copyDictionary;
98 /* If known, the number of bytes to allocate for the key field in the SecKey struct. */
99 int extraBytes;
100 } SecKeyDescriptor;
101
102 /*!
103 @function SecKeyGetAlgorithmID
104 @abstract Returns a pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure for the given key.
105 @param key A key reference.
106 @param algid On return, a pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure.
107 @result A result code. See "Security Error Codes" (SecBase.h).
108 */
109 OSStatus SecKeyGetAlgorithmID(SecKeyRef key, const CSSM_X509_ALGORITHM_IDENTIFIER **algid)
110 DEPRECATED_IN_MAC_OS_X_VERSION_10_8_AND_LATER;
111
112 enum {
113 kSecNullAlgorithmID = 0,
114 kSecRSAAlgorithmID = 1,
115 kSecDSAAlgorithmID = 2, /* unsupported, just here for reference. */
116 kSecECDSAAlgorithmID = 3,
117 };
118
119 /*!
120 @function SecKeyGetAlgorithmId
121 @abstract Returns an enumerated constant value which identifies the algorithm for the given key.
122 @param key A key reference.
123 @result An algorithm identifier.
124 */
125 CFIndex SecKeyGetAlgorithmId(SecKeyRef key)
126 __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_NA);
127
128 /*!
129 @function SecKeyGetStrengthInBits
130 @abstract Returns key strength in bits for the given key.
131 @param key A key reference.
132 @param algid A pointer to a CSSM_X509_ALGORITHM_IDENTIFIER structure, as returned from a call to SecKeyGetAlgorithmID.
133 @param strength On return, the key strength in bits.
134 @result A result code. See "Security Error Codes" (SecBase.h).
135 */
136 OSStatus SecKeyGetStrengthInBits(SecKeyRef key, const CSSM_X509_ALGORITHM_IDENTIFIER *algid, unsigned int *strength);
137
138 /*!
139 @function SecKeyImportPair
140 @abstract Takes an asymmetric key pair and stores it in the keychain specified by the keychain parameter.
141 @param keychainRef A reference to the keychain in which to store the private and public key items. Specify NULL for the default keychain.
142 @param publicCssmKey A CSSM_KEY which is valid for the CSP returned by SecKeychainGetCSPHandle(). This may be a normal key or reference key.
143 @param privateCssmKey A CSSM_KEY which is valid for the CSP returned by SecKeychainGetCSPHandle(). This may be a normal key or reference key.
144 @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.
145 @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.
146 @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.
147 @result A result code. See "Security Error Codes" (SecBase.h).
148 @deprecated in 10.5 and later. Use the SecKeychainItemImport function instead; see <Security/SecImportExport.h>
149 */
150 OSStatus SecKeyImportPair(
151 SecKeychainRef keychainRef,
152 const CSSM_KEY *publicCssmKey,
153 const CSSM_KEY *privateCssmKey,
154 SecAccessRef initialAccess,
155 SecKeyRef* publicKey,
156 SecKeyRef* privateKey)
157 DEPRECATED_IN_MAC_OS_X_VERSION_10_5_AND_LATER;
158
159 /*!
160 @function SecKeyCreate
161 @abstract Create a key reference from the supplied key data.
162 @param allocator CFAllocator to allocate the key data. Pass NULL to use the default allocator.
163 @param keyClass A descriptor for the particular class of key that is being created.
164 @param keyData Data from which to create the key. Specify the format of this data in the encoding parameter.
165 @param keyDataLength Length of the data pointed to by keyData.
166 @param encoding A value of type SecKeyEncoding which describes the format of keyData.
167 @result A key reference.
168 @discussion Warning: this function is NOT intended for use outside the Security stack in its current state. <rdar://3201885>
169 IMPORTANT: on Mac OS X 10.5 and earlier, the SecKeyCreate function had a different parameter list.
170 The current parameter list matches the iPhone OS implementation. Existing clients of this function
171 on Mac OS X (and there should not be any outside the Security stack, per the warning above) must
172 migrate to the replacement function, SecKeyCreateWithCSSMKey.
173 */
174 SecKeyRef SecKeyCreate(CFAllocatorRef allocator,
175 const SecKeyDescriptor *keyClass, const uint8_t *keyData,
176 CFIndex keyDataLength, SecKeyEncoding encoding);
177
178 /*!
179 @function SecKeyCreateWithCSSMKey
180 @abstract Generate a temporary floating key reference for a CSSM_KEY.
181 @param key A pointer to a CSSM_KEY structure.
182 @param keyRef On return, a key reference.
183 @result A result code. See "Security Error Codes" (SecBase.h).
184 @discussion Warning: this function is NOT intended for use outside the Security stack in its current state. <rdar://3201885>
185 */
186 OSStatus SecKeyCreateWithCSSMKey(const CSSM_KEY *key, SecKeyRef* keyRef);
187
188 /*!
189 @enum Dictionary key constants for SecKeyGeneratePair API.
190 @discussion Predefined key constants used to get or set values in a dictionary.
191 @constant kSecPrivateKeyAttrs The value for this key is a CFDictionaryRef
192 containing attributes specific for the private key to be generated.
193 @constant kSecPublicKeyAttrs The value for this key is a CFDictionaryRef
194 containing attributes specific for the public key to be generated.
195 */
196 extern CFTypeRef kSecPrivateKeyAttrs;
197 extern CFTypeRef kSecPublicKeyAttrs;
198
199 /*!
200 @function SecKeyGeneratePair
201 @abstract Generate a private/public keypair.
202 @param parameters A dictionary containing one or more key-value pairs.
203 See the discussion sections below for a complete overview of options.
204 @param publicKey On return, a SecKeyRef reference to the public key.
205 @param privateKey On return, a SecKeyRef reference to the private key.
206 @result A result code. See "Security Error Codes" (SecBase.h).
207 @discussion In order to generate a keypair the parameters dictionary must
208 at least contain the following keys:
209
210 * kSecAttrKeyType with a value being kSecAttrKeyTypeRSA or any other
211 kSecAttrKeyType defined in SecItem.h
212 * kSecAttrKeySizeInBits with a value being a CFNumberRef or CFStringRef
213 containing the requested key size in bits. Example sizes for RSA
214 keys are: 512, 768, 1024, 2048.
215
216 The values below may be set either in the top-level dictionary or in a
217 dictionary that is the value of the kSecPrivateKeyAttrs or
218 kSecPublicKeyAttrs key in the top-level dictionary. Setting these
219 attributes explicitly will override the defaults below. See SecItem.h
220 for detailed information on these attributes including the types of
221 the values.
222
223 * kSecAttrLabel default NULL
224 * kSecAttrIsPermanent if this key is present and has a Boolean
225 value of true, the key or key pair will be added to the default
226 keychain.
227 * kSecAttrApplicationTag default NULL
228 * kSecAttrEffectiveKeySize default NULL same as kSecAttrKeySizeInBits
229 * kSecAttrCanEncrypt default false for private keys, true for public keys
230 * kSecAttrCanDecrypt default true for private keys, false for public keys
231 * kSecAttrCanDerive default true
232 * kSecAttrCanSign default true for private keys, false for public keys
233 * kSecAttrCanVerify default false for private keys, true for public keys
234 * kSecAttrCanWrap default false for private keys, true for public keys
235 * kSecAttrCanUnwrap default true for private keys, false for public keys
236
237 */
238 OSStatus SecKeyGeneratePair(CFDictionaryRef parameters,
239 SecKeyRef *publicKey, SecKeyRef *privateKey);
240
241
242 /*!
243 @function SecKeyRawSign
244 @abstract Given a private key and data to sign, generate a digital signature.
245 @param key Private key with which to sign.
246 @param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
247 @param dataToSign The data to be signed, typically the digest of the actual data.
248 @param dataToSignLen Length of dataToSign in bytes.
249 @param sig Pointer to buffer in which the signature will be returned.
250 @param sigLen IN/OUT maximum length of sig buffer on input, actualy length of sig on output.
251 @result A result code. See "Security Error Codes" (SecBase.h).
252 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
253 will be performed prior to signing. If this argument is kSecPaddingNone,
254 the incoming data will be signed "as is".
255
256 When PKCS1 padding is performed, the maximum length of data that can
257 be signed is the value returned by SecKeyGetBlockSize() - 11.
258
259 NOTE: The behavior this function with kSecPaddingNone is undefined if the
260 first byte of dataToSign is zero; there is no way to verify leading zeroes
261 as they are discarded during the calculation.
262
263 If you want to generate a proper PKCS1 style signature with DER encoding of
264 the digest type - and the dataToSign is a SHA1 digest - use kSecPaddingPKCS1SHA1.
265 */
266 OSStatus SecKeyRawSign(
267 SecKeyRef key,
268 SecPadding padding,
269 const uint8_t *dataToSign,
270 size_t dataToSignLen,
271 uint8_t *sig,
272 size_t *sigLen);
273
274
275 /*!
276 @function SecKeyRawVerify
277 @abstract Given a public key, data which has been signed, and a signature, verify the signature.
278 @param key Public key with which to verify the signature.
279 @param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
280 @param signedData The data over which sig is being verified, typically the digest of the actual data.
281 @param signedDataLen Length of signedData in bytes.
282 @param sig Pointer to the signature to verify.
283 @param sigLen Length of sig in bytes.
284 @result A result code. See "Security Error Codes" (SecBase.h).
285 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
286 will be checked during verification. If this argument is kSecPaddingNone,
287 the incoming data will be compared directly to sig.
288
289 If you are verifying a proper PKCS1-style signature, with DER encoding of the digest
290 type - and the signedData is a SHA1 digest - use kSecPaddingPKCS1SHA1.
291 */
292 OSStatus SecKeyRawVerify(
293 SecKeyRef key,
294 SecPadding padding,
295 const uint8_t *signedData,
296 size_t signedDataLen,
297 const uint8_t *sig,
298 size_t sigLen);
299
300
301 /*!
302 @function SecKeyEncrypt
303 @abstract Encrypt a block of plaintext.
304 @param key Public key with which to encrypt the data.
305 @param padding See Padding Types above, typically kSecPaddingPKCS1.
306 @param plainText The data to encrypt.
307 @param plainTextLen Length of plainText in bytes, this must be less
308 or equal to the value returned by SecKeyGetBlockSize().
309 @param cipherText Pointer to the output buffer.
310 @param cipherTextLen On input, specifies how much space is available at
311 cipherText; on return, it is the actual number of cipherText bytes written.
312 @result A result code. See "Security Error Codes" (SecBase.h).
313 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
314 will be performed prior to encryption. If this argument is kSecPaddingNone,
315 the incoming data will be encrypted "as is".
316
317 When PKCS1 padding is performed, the maximum length of data that can
318 be encrypted is the value returned by SecKeyGetBlockSize() - 11.
319
320 When memory usage is a critical issue, note that the input buffer
321 (plainText) can be the same as the output buffer (cipherText).
322 */
323 OSStatus SecKeyEncrypt(
324 SecKeyRef key,
325 SecPadding padding,
326 const uint8_t *plainText,
327 size_t plainTextLen,
328 uint8_t *cipherText,
329 size_t *cipherTextLen);
330
331
332 /*!
333 @function SecKeyDecrypt
334 @abstract Decrypt a block of ciphertext.
335 @param key Private key with which to decrypt the data.
336 @param padding See SecPadding types above; typically kSecPaddingPKCS1.
337 @param cipherText The data to decrypt.
338 @param cipherTextLen Length of cipherText in bytes; this must be less
339 or equal to the value returned by SecKeyGetBlockSize().
340 @param plainText Pointer to the output buffer.
341 @param plainTextLen On input, specifies how much space is available at
342 plainText; on return, it is the actual number of plainText bytes written.
343 @result A result code. See "Security Error Codes" (SecBase.h).
344 @discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
345 will be removed after decryption. If this argument is kSecPaddingNone,
346 the decrypted data will be returned "as is".
347
348 When memory usage is a critical issue, note that the input buffer
349 (plainText) can be the same as the output buffer (cipherText).
350 */
351 OSStatus SecKeyDecrypt(
352 SecKeyRef key, /* Private key */
353 SecPadding padding, /* kSecPaddingNone, kSecPaddingPKCS1, kSecPaddingOAEP */
354 const uint8_t *cipherText,
355 size_t cipherTextLen, /* length of cipherText */
356 uint8_t *plainText,
357 size_t *plainTextLen); /* IN/OUT */
358
359 OSStatus SecKeyVerifyDigest(
360 SecKeyRef key, /* Private key */
361 const SecAsn1AlgId *algId, /* algorithm oid/params */
362 const uint8_t *digestData, /* signature over this digest */
363 size_t digestDataLen, /* length of dataToDigest */
364 const uint8_t *sig, /* signature to verify */
365 size_t sigLen); /* length of sig */
366
367 OSStatus SecKeySignDigest(
368 SecKeyRef key, /* Private key */
369 const SecAsn1AlgId *algId, /* algorithm oid/params */
370 const uint8_t *digestData, /* signature over this digest */
371 size_t digestDataLen, /* length of digestData */
372 uint8_t *sig, /* signature, RETURNED */
373 size_t *sigLen); /* IN/OUT */
374
375
376 /* These are the named curves we support. These values come from RFC 4492
377 section 5.1.1, with the exception of SSL_Curve_None which means
378 "ECDSA not negotiated". */
379 typedef enum
380 {
381 kSecECCurveNone = -1,
382 kSecECCurveSecp256r1 = 23,
383 kSecECCurveSecp384r1 = 24,
384 kSecECCurveSecp521r1 = 25
385 } SecECNamedCurve;
386
387 /* Return a named curve enum for ecPrivateKey. */
388 SecECNamedCurve SecECKeyGetNamedCurve(SecKeyRef ecPrivateKey);
389 CFDataRef SecECKeyCopyPublicBits(SecKeyRef key);
390
391 /* Given an RSA public key in encoded form return a SecKeyRef representing
392 that key. Supported encodings are kSecKeyEncodingPkcs1. */
393 SecKeyRef SecKeyCreateRSAPublicKey(CFAllocatorRef allocator,
394 const uint8_t *keyData, CFIndex keyDataLength,
395 SecKeyEncoding encoding);
396
397 CFDataRef SecKeyCopyModulus(SecKeyRef rsaPublicKey);
398 CFDataRef SecKeyCopyExponent(SecKeyRef rsaPublicKey);
399
400 #if defined(__cplusplus)
401 }
402 #endif
403
404 #endif /* !_SECURITY_SECKEYPRIV_H_ */
405