5 * Created on 11/16/2010
7 * Copyright (c) 2010,2011,2012,2014,2015 Apple Inc. All rights reserved.
11 #ifndef _CORECRYPTO_CCRSA_H_
12 #define _CORECRYPTO_CCRSA_H_
14 #include <corecrypto/cc.h>
15 #include <corecrypto/ccdigest.h>
16 #include <corecrypto/ccrng.h>
17 #include <corecrypto/cczp.h>
20 // Apple does not generate keys of greater than 4096 bits
21 // This limit is relaxed to accommodate potential third-party consumers
22 #define CCRSA_KEYGEN_MAX_NBITS 8192
24 struct ccrsa_full_ctx
{
25 __CCZP_ELEMENTS_DEFINITIONS(pb_
)
26 } CC_ALIGNED(CCN_UNIT_SIZE
);
28 struct ccrsa_pub_ctx
{
29 __CCZP_ELEMENTS_DEFINITIONS(pb_
)
30 } CC_ALIGNED(CCN_UNIT_SIZE
);
32 struct ccrsa_priv_ctx
{
33 __CCZP_ELEMENTS_DEFINITIONS(pv_
)
34 } CC_ALIGNED(CCN_UNIT_SIZE
);
36 typedef struct ccrsa_full_ctx
* ccrsa_full_ctx_t
;
37 typedef struct ccrsa_pub_ctx
* ccrsa_pub_ctx_t
;
38 typedef struct ccrsa_priv_ctx
* ccrsa_priv_ctx_t
;
41 public key cczp d=e^-1 mod phi(m) priv key cczp priv key cczq dp, dq, qinv
44 +-------+------+-------+------++------++-------+------+---------++-------+------+---------++-------+-------+---------+
45 | zm_hd | m[n] |mr[n+1]| e[n] || d[n] || zp_hd |p[n/2]|pr[n/2+1]|| zq_hd |q[n/2]|qr[n/2+1]||dp[n/2]|dq[n/2]|qinv[n/2]|
46 +-------+------+-------+------++------++-------+------+---------++-------+------+---------++-------+-------+---------+
49 /* Return the size of an ccec_full_ctx where each ccn is _size_ bytes. Get _size_ through ccn_sizeof(nbits) */
51 /* Return the size of an ccec_full_ctx where each ccn is _size_ bytes. */
53 #define ccrsa_pub_ctx_size(_size_) (sizeof(struct cczp) + CCN_UNIT_SIZE + 3 * (_size_))
54 #define ccrsa_priv_ctx_size(_size_) ((sizeof(struct cczp) + CCN_UNIT_SIZE) * 2 + 7 * ccn_sizeof(ccn_bitsof_size(_size_)/2 + 1))
55 #define ccrsa_full_ctx_size(_size_) (ccrsa_pub_ctx_size(_size_) + _size_ + ccrsa_priv_ctx_size(_size_))
57 /* Declare a fully scheduled rsa key. Size is the size in bytes each ccn in
58 the key. For example to declare (on the stack or in a struct) a 1021 bit
59 rsa public key named foo use ccrsa_pub_ctx_decl(ccn_sizeof(1021), foo).
61 #define ccrsa_full_ctx_decl(_size_, _name_) cc_ctx_decl(struct ccrsa_full_ctx, ccrsa_full_ctx_size(_size_), _name_)
62 #define ccrsa_full_ctx_clear(_size_, _name_) cc_clear(ccrsa_full_ctx_size(_size_), _name_)
63 #define ccrsa_pub_ctx_decl(_size_, _name_) cc_ctx_decl(struct ccrsa_pub_ctx, ccrsa_pub_ctx_size(_size_), _name_)
64 #define ccrsa_pub_ctx_clear(_size_, _name_) cc_clear(ccrsa_pub_ctx_size(_size_), _name_)
66 // accessors to ccrsa full and public key fields. */
67 // The offsets are computed using pb_ccn. If any object other than ccrsa_full_ctx_t
68 // or ccrsa_pub_ctx_t is passed to the macros, compiler error is generated.
70 #define ccrsa_ctx_zm(_ctx_) ((cczp_t)(_ctx_))
71 #define ccrsa_ctx_n(_ctx_) (ccrsa_ctx_zm(_ctx_)->n)
72 #define ccrsa_ctx_m(_ctx_) ((_ctx_)->pb_ccn)
74 #define ccrsa_ctx_e(_ctx_) (ccrsa_ctx_m(_ctx_) + 2 * ccrsa_ctx_n(_ctx_) + 1)
75 #define ccrsa_ctx_d(_ctx_) (ccrsa_ctx_m(_ctx_) + 3 * ccrsa_ctx_n(_ctx_) + 1)
77 // accessors to ccrsa private key fields
78 // The offsets are computed using pv_ccn. If any object other than ccrsa_priv_ctx_t
79 // is passed to the macros, compiler error is generated.
80 #define ccrsa_ctx_private_zp(FK) ((cczp_t)ccrsa_get_private_ctx_ptr(FK))
81 #define ccrsa_ctx_private_zq(FK) ((cczp_t)((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 2 * ccrsa_ctx_private_zp(FK)->n + 1))
82 #define ccrsa_ctx_private_dp(FK) ((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 4 * ccrsa_ctx_private_zp(FK)->n + 2 + ccn_nof_size(sizeof(struct cczp)))
83 #define ccrsa_ctx_private_dq(FK) ((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 5 * ccrsa_ctx_private_zp(FK)->n + 2 + ccn_nof_size(sizeof(struct cczp)))
84 #define ccrsa_ctx_private_qinv(FK) ((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 6 * ccrsa_ctx_private_zp(FK)->n + 2 + ccn_nof_size(sizeof(struct cczp)))
86 /* rvalue accessors to ccec_key fields. */
88 ccrsa_priv_ctx_t
ccrsa_get_private_ctx_ptr(ccrsa_full_ctx_t fk
) {
89 ccrsa_priv_ctx_t priv
= (ccrsa_priv_ctx_t
)(ccrsa_ctx_d(fk
)+ccrsa_ctx_n(fk
));
94 @function ccrsa_ctx_public
95 @abstract gets the public key from full key
96 @param fk RSA full key
97 @result Returns RSA public ker
100 ccrsa_pub_ctx_t
ccrsa_ctx_public(ccrsa_full_ctx_t fk
) {
101 return (ccrsa_pub_ctx_t
) fk
;
104 /* Return exact key bit size */
106 size_t ccrsa_pubkeylength(ccrsa_pub_ctx_t pubk
);
108 /* PKCS1 pad_markers */
109 #define CCRSA_PKCS1_PAD_SIGN 1
110 #define CCRSA_PKCS1_PAD_ENCRYPT 2
112 /* Initialize key based on modulus and e as cc_unit. key->zp.n must already be set. */
113 CC_NONNULL((1, 2, 3))
114 int ccrsa_init_pub(ccrsa_pub_ctx_t key
, const cc_unit
*modulus
,
118 @function ccrsa_make_priv
119 @abstract Initialize public and private key based on modulus and e, p and q as big endian byte arrays;
121 @param full_ctx Initialized context with full_ctx->zp.n already set to 2*ccn_nof_size(p_mbytes)
122 @param exp_mbytes Number of bytes in big endian e.
123 @param exp_in pointer to big endian exponent e (may have leading 0's).
124 @param p_mbytes Number of bytes in big endian p.
125 @param p_in Pointer to the rsa p.
126 @param q_mbytes Number of bytes in big endian q.
127 @param q_in Pointer to the rsa q.
128 @result 0 iff successful.
130 @discussion full_ctx->zp.n must already be set to 2*ccn_nof_size(p_mbytes), witt the expectation that p_mbytes>q_mbytes.
131 e is the public exponent, and exp_mbytes<= 2*p_mbytes.
132 The output is a fully formed rsa context with N=pq, d=e^{-1} mod phi(N), and appropriate inverses of different associated values precomputed
133 to speed computation.
136 int ccrsa_make_priv(ccrsa_full_ctx_t full_ctx
,
138 const uint8_t *exp_in
,
142 const uint8_t *q_in
);
144 /* Initialize key based on modulus and e as big endian byte array
145 key->zp.n must already be set. */
146 CC_NONNULL((1, 3, 5))
147 int ccrsa_make_pub(ccrsa_pub_ctx_t pubk
,
148 size_t exp_nbytes
, const uint8_t *exp
,
149 size_t mod_nbytes
, const uint8_t *mod
);
151 /* Do a public key crypto operation (typically verify or encrypt) on in and put
152 the result in out. Both in and out should be cc_unit aligned and
153 ccrsa_key_n(key) units long. Clients should use ccn_read_uint() to
154 convert bytes to a cc_unit to use for this API.*/
155 CC_NONNULL((1, 2, 3))
156 int ccrsa_pub_crypt(ccrsa_pub_ctx_t key
, cc_unit
*out
, const cc_unit
*in
);
158 /* Generate an nbit rsa key pair in key, which should be allocated using
159 ccrsa_full_ctx_decl(ccn_sizeof(1024), rsa_ctx). The unsigned big endian
160 byte array exponent e of length e_size is used as the exponent. It's an
161 error to call this function with an exponent larger than nbits. rng
162 must be a pointer to an initialized struct ccrng_state. */
163 CC_NONNULL((2, 4, 5))
164 int ccrsa_generate_key(size_t nbits
, ccrsa_full_ctx_t rsa_ctx
,
165 size_t e_size
, const void *e
, struct ccrng_state
*rng
) CC_WARN_RESULT
;
167 /* Generate RSA key in conformance with FIPS186-4 standard.
168 The first RNG `rng` will be used to generate p and q.
169 The second RNG `rng_mr` will be used only for primality testing.
170 This is relevant only for testing, just pass the same RNG twice. */
171 CC_NONNULL((2, 4, 5, 6))
173 ccrsa_generate_fips186_key(size_t nbits
, ccrsa_full_ctx_t fk
,
174 size_t e_size
, const void *eBytes
,
175 struct ccrng_state
*rng
, struct ccrng_state
*rng_mr
) CC_WARN_RESULT
;
177 /* Construct RSA key from fix input in conformance with FIPS186-4 standard */
178 CC_NONNULL((3, 5, 7, 9, 11, 13, 15, 16))
180 ccrsa_make_fips186_key(size_t nbits
,
181 const cc_size e_n
, const cc_unit
*e
,
182 const cc_size xp1Len
, const cc_unit
*xp1
, const cc_size xp2Len
, const cc_unit
*xp2
,
183 const cc_size xpLen
, const cc_unit
*xp
,
184 const cc_size xq1Len
, const cc_unit
*xq1
, const cc_size xq2Len
, const cc_unit
*xq2
,
185 const cc_size xqLen
, const cc_unit
*xq
,
187 cc_size
*np
, cc_unit
*r_p
,
188 cc_size
*nq
, cc_unit
*r_q
,
189 cc_size
*nm
, cc_unit
*r_m
,
190 cc_size
*nd
, cc_unit
*r_d
);
193 * @brief ccrsa_sign_pss() generates RSASSA-PSS signature in PKCS1-V2 format
195 * note that in RSASSA-PSS, salt length is part of the signature as specified in ASN1
196 * RSASSA-PSS-params ::= SEQUENCE {
197 * hashAlgorithm [0] HashAlgorithm DEFAULT sha1,
198 * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1,
199 * saltLength [2] INTEGER DEFAULT 20,
200 * trailerField [3] TrailerField DEFAULT trailerFieldBC
203 * FIPS 186-4 for RSASSA-PSS:
204 * .... Both signature schemes are approved for use, but additional constraints are imposed beyond those specified in PKCS #1 v2.1.....
206 * • If nlen = 1024 bits (i.e., 128 bytes), and the output length of the approved hash function output block is 512 bits (i.e., 64 bytes), then the length (in bytes) of the salt (sLen) shall satisfy 0 ≤ sLen ≤ hLen – 2,
207 * • Otherwise, the length (in bytes) of the salt (sLen) shall satisfy 0 ≤ sLen ≤ hLen, where hLen is the length of the hash function output block (in bytes).
210 * • CAVS test vectors are not very useful in the case of RSA-PSS, because they only validate the exponentiation part of the signature. See: http://csrc.nist.gov/groups/STM/cavp/documents/components/RSA2SP1VS.pdf
212 * @param key The RSA key
213 * @param hashAlgorithm The hash algorithm used to generate mHash from the original message. It is also used inside the PSS encoding function. This is also the hash function to be used in the mask generation function (MGF)
214 * @param MgfHashAlgorithm The hash algorithm for thr mask generation function
215 * @param rng Random number geberator to generate salt in PSS encoding
216 * @param saltSize Intended length of the salt
217 * @param hSize Length of message hash . Must be equal to hashAlgorithm->output_size
218 * @param mHash The input that needs to be signed. This is the hash of message M with length of hLen
220 * @param sig The signature output
221 * @param sigSize The length of generated signature in bytes, which equals the size of the RSA modulus.
222 * @return 0:ok, non-zero:error
224 CC_NONNULL((2, 3, 5, 7, 8, 9))
225 int ccrsa_sign_pss(ccrsa_full_ctx_t key
,
226 const struct ccdigest_info
* hashAlgorithm
, const struct ccdigest_info
* MgfHashAlgorithm
,
227 size_t saltSize
, struct ccrng_state
*rng
,
228 size_t hSize
, const uint8_t *mHash
,
229 size_t *sigSize
, uint8_t *sig
);
231 CC_NONNULL((2, 3, 5, 7, 9))
232 int ccrsa_verify_pss(ccrsa_pub_ctx_t key
,
233 const struct ccdigest_info
* di
, const struct ccdigest_info
* MgfDi
,
234 size_t digestSize
, const uint8_t *digest
,
235 size_t sigSize
, const uint8_t *sig
,
236 size_t saltSize
, bool *valid
);
239 @function ccrsa_sign_pkcs1v15
240 @abstract RSA signature with PKCS#1 v1.5 format per PKCS#1 v2.2
243 @param oid OID describing the type of digest passed in
244 @param digest_len Byte length of the digest
245 @param digest Byte array of digest_len bytes containing the digest
246 @param sig_len Pointer to the number of byte allocate for sig.
247 Output the exact size of the signature.
248 @param sig Pointer to the allocated buffer of size *sig_len
249 for the output signature
251 @result 0 iff successful.
253 @discussion Null OID is a special case, required to support RFC 4346 where the padding
254 is based on SHA1+MD5. In general it is not recommended to use a NULL OID,
255 except when strictly required for interoperability
258 CC_NONNULL((1, 4, 5, 6))
259 int ccrsa_sign_pkcs1v15(ccrsa_full_ctx_t key
, const uint8_t *oid
,
260 size_t digest_len
, const uint8_t *digest
,
261 size_t *sig_len
, uint8_t *sig
);
265 @function ccrsa_verify_pkcs1v15
266 @abstract RSA signature with PKCS#1 v1.5 format per PKCS#1 v2.2
268 @param key Public key
269 @param oid OID describing the type of digest passed in
270 @param digest_len Byte length of the digest
271 @param digest Byte array of digest_len bytes containing the digest
272 @param sig_len Number of byte of the signature sig.
273 @param sig Pointer to the signature buffer of sig_len
274 @param valid Output boolean, true if the signature is valid.
276 @result 0 iff successful.
278 @discussion Null OID is a special case, required to support RFC 4346
279 where the padding is based on SHA1+MD5. In general it is not
280 recommended to use a NULL OID, except when strictly required for
283 CC_NONNULL((1, 4, 6, 7))
284 int ccrsa_verify_pkcs1v15(ccrsa_pub_ctx_t key
, const uint8_t *oid
,
285 size_t digest_len
, const uint8_t *digest
,
286 size_t sig_len
, const uint8_t *sig
,
290 @function ccder_encode_rsa_pub_size
291 @abstract Calculate size of public key export format data package.
293 @param key Public key
295 @result Returns size required for encoding.
299 size_t ccder_encode_rsa_pub_size(const ccrsa_pub_ctx_t key
);
302 @function ccrsa_export_priv_pkcs1
303 @abstract Export a public key.
305 @param key Public key
306 @param der Beginning of output DER buffer
307 @param der_end End of output DER buffer
310 CC_NONNULL((1, 2, 3))
311 uint8_t *ccder_encode_rsa_pub(const ccrsa_pub_ctx_t key
, uint8_t *der
, uint8_t *der_end
);
315 @function ccder_encode_rsa_priv_size
316 @abstract Calculate size of full key exported in PKCS#1 format.
320 @result Returns size required for encoding.
324 size_t ccder_encode_rsa_priv_size(const ccrsa_full_ctx_t key
);
327 @function ccder_encode_rsa_priv
328 @abstract Export a full key in PKCS#1 format.
331 @param der Beginning of output DER buffer
332 @param der_end End of output DER buffer
335 CC_NONNULL((1, 2, 3))
336 uint8_t *ccder_encode_rsa_priv(const ccrsa_full_ctx_t key
, const uint8_t *der
, uint8_t *der_end
);
339 @function ccder_decode_rsa_pub_n
340 @abstract Calculate "n" for a public key imported from a data package.
343 @param der Beginning of input DER buffer
344 @param der_end End of input DER buffer
346 @result the "n" of the RSA key that would result from the import. This can be used
347 to declare the key itself.
351 cc_size
ccder_decode_rsa_pub_n(const uint8_t *der
, const uint8_t *der_end
);
354 @function ccder_decode_rsa_pub
355 @abstract Import a public RSA key from a package in public key format.
358 @param key Public key (n must be set)
359 @param der Beginning of input DER buffer
360 @param der_end End of input DER buffer
362 @result Key is initialized using the data in the public key message.
365 CC_NONNULL((1, 2, 3))
366 const uint8_t *ccder_decode_rsa_pub(const ccrsa_pub_ctx_t key
, const uint8_t *der
, const uint8_t *der_end
);
369 @function ccder_decode_rsa_pub_x509_n
370 @abstract Calculate "n" for a public key imported from a data package in x509 format
372 @param der Beginning of input DER buffer
373 @param der_end End of input DER buffer
375 @result the "n" of the RSA key that would result from the import. This can be used
376 to declare the key itself.
380 cc_size
ccder_decode_rsa_pub_x509_n(const uint8_t *der
, const uint8_t *der_end
);
383 @function ccder_decode_rsa_pub_x509
384 @abstract Import a public RSA key from a package in x509 format.
386 @param key Public key (n must be set)
387 @param der Beginning of input DER buffer
388 @param der_end End of input DER buffer
390 @result Key is initialized using the data in the public key message.
393 CC_NONNULL((1, 2, 3))
394 const uint8_t *ccder_decode_rsa_pub_x509(const ccrsa_pub_ctx_t key
, const uint8_t *der
, const uint8_t *der_end
);
398 @function ccder_decode_rsa_priv_n
399 @abstract Calculate "n" for a private key imported from a data package.
401 @param der Beginning of input DER buffer
402 @param der_end End of input DER buffer
404 @result the "n" of the RSA key that would result from the import. This can be used
405 to declare the key itself.
409 cc_size
ccder_decode_rsa_priv_n(const uint8_t *der
, const uint8_t *der_end
);
412 @function ccder_decode_rsa_priv
413 @abstract Import a private RSA key from a package in PKCS#1 format.
415 @param key Full key (n must be set)
416 @param der Beginning of input DER buffer
417 @param der_end End of input DER buffer
419 @result Key is initialized using the data in the public key message.
422 CC_NONNULL((1, 2, 3))
423 const uint8_t *ccder_decode_rsa_priv(const ccrsa_full_ctx_t key
, const uint8_t *der
, const uint8_t *der_end
);
426 @function ccrsa_export_pub_size
427 @abstract Calculate size of public key exported data package.
429 @param key Public key
431 @result Returns size required for encoding.
434 CC_INLINE
CC_NONNULL((1))
435 size_t ccrsa_export_pub_size(const ccrsa_pub_ctx_t key
) {
436 return ccder_encode_rsa_pub_size(key
);
440 @function ccrsa_export_pub
441 @abstract Export a public key in public key format.
443 @param key Public key
444 @param out_len Allocated size
445 @param out Output buffer
449 int ccrsa_export_pub(const ccrsa_pub_ctx_t key
, size_t out_len
, uint8_t *out
);
451 @function ccrsa_import_pub_n
452 @abstract Calculate "n" for a public key imported from a data package.
454 @param inlen Length of public key package data
455 @param der pointer to public key package data
457 @result the "n" of the RSA key that would result from the import. This can be used
458 to declare the key itself.
461 CC_INLINE
CC_NONNULL((2))
462 cc_size
ccrsa_import_pub_n(size_t inlen
, const uint8_t *der
) {
463 cc_size size
= ccder_decode_rsa_pub_x509_n(der
, der
+ inlen
);
465 size
= ccder_decode_rsa_pub_n(der
, der
+ inlen
);
471 @function ccrsa_import_pub
472 @abstract Import a public RSA key from a package in public key format.
474 @param key Public key (n must be set)
475 @param inlen Length of public key package data
476 @param der pointer to public key package data
478 @result Key is initialized using the data in the public key message.
482 int ccrsa_import_pub(ccrsa_pub_ctx_t key
, size_t inlen
, const uint8_t *der
);
485 @function ccrsa_export_priv_size
486 @abstract Calculate size of full key exported in PKCS#1 format.
490 @result Returns size required for encoding.
493 CC_INLINE
CC_NONNULL((1))
494 size_t ccrsa_export_priv_size(const ccrsa_full_ctx_t key
) {
495 return ccder_encode_rsa_priv_size(key
);
499 @function ccrsa_export_priv
500 @abstract Export a full key in PKCS#1 format.
503 @param out_len Allocated size
504 @param out Output buffer
507 CC_INLINE
CC_NONNULL((1, 3))
508 int ccrsa_export_priv(const ccrsa_full_ctx_t key
, size_t out_len
, uint8_t *out
) {
509 return (ccder_encode_rsa_priv(key
, out
, out
+out_len
) != out
);
513 @function ccrsa_import_priv_n
514 @abstract Calculate size of full key exported in PKCS#1 format.
516 @param inlen Length of PKCS#1 package data
517 @param der pointer to PKCS#1 package data
519 @result the "n" of the RSA key that would result from the import. This can be used
520 to declare the key itself.
523 CC_INLINE
CC_NONNULL((2))
524 cc_size
ccrsa_import_priv_n(size_t inlen
, const uint8_t *der
) {
525 return ccder_decode_rsa_priv_n(der
, der
+ inlen
);
529 @function ccrsa_import_priv
530 @abstract Import a full RSA key from a package in PKCS#1 format.
532 @param key Full key (n must be set)
533 @param inlen Length of PKCS#1 package data
534 @param der pointer to PKCS#1 package data
536 @result Key is initialized using the data in the PKCS#1 message.
539 CC_INLINE
CC_NONNULL((1, 3))
540 int ccrsa_import_priv(ccrsa_full_ctx_t key
, size_t inlen
, const uint8_t *der
) {
541 return (ccder_decode_rsa_priv(key
, der
, der
+inlen
) == NULL
);
546 int ccrsa_get_pubkey_components(const ccrsa_pub_ctx_t pubkey
, uint8_t *modulus
, size_t *modulusLength
, uint8_t *exponent
, size_t *exponentLength
);
549 int ccrsa_get_fullkey_components(const ccrsa_full_ctx_t key
, uint8_t *modulus
, size_t *modulusLength
, uint8_t *exponent
, size_t *exponentLength
,
550 uint8_t *p
, size_t *pLength
, uint8_t *q
, size_t *qLength
);
554 @function ccrsa_dump_public_key
555 @abstract Print a rsa public key in the console (printf)
557 @param key Public key
559 void ccrsa_dump_public_key(ccrsa_pub_ctx_t key
);
562 @function ccrsa_dump_full_key
563 @abstract Print a rsa private key in the console (printf)
565 @param key Public key
567 void ccrsa_dump_full_key(ccrsa_full_ctx_t key
);
569 #endif /* _CORECRYPTO_CCRSA_H_ */