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