1 /**
2  * \file pk.h
3  *
4  * \brief Public Key abstraction layer
5  */
6 /*
7  *  Copyright The Mbed TLS Contributors
8  *  SPDX-License-Identifier: Apache-2.0
9  *
10  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
11  *  not use this file except in compliance with the License.
12  *  You may obtain a copy of the License at
13  *
14  *  http://www.apache.org/licenses/LICENSE-2.0
15  *
16  *  Unless required by applicable law or agreed to in writing, software
17  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  *  See the License for the specific language governing permissions and
20  *  limitations under the License.
21  */
22 
23 #ifndef MBEDTLS_PK_H
24 #define MBEDTLS_PK_H
25 
26 #if !defined(MBEDTLS_CONFIG_FILE)
27 #include "mbedtls/config.h"
28 #else
29 #include MBEDTLS_CONFIG_FILE
30 #endif
31 
32 #include "mbedtls/md.h"
33 
34 #if defined(MBEDTLS_RSA_C)
35 #include "mbedtls/rsa.h"
36 #endif
37 
38 #if defined(MBEDTLS_ECP_C)
39 #include "mbedtls/ecp.h"
40 #endif
41 
42 #if defined(MBEDTLS_ECDSA_C)
43 #include "mbedtls/ecdsa.h"
44 #endif
45 
46 #if defined(MBEDTLS_USE_PSA_CRYPTO)
47 #include "psa/crypto.h"
48 #endif
49 
50 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
51     !defined(inline) && !defined(__cplusplus)
52 #define inline __inline
53 #endif
54 
55 /** Memory allocation failed. */
56 #define MBEDTLS_ERR_PK_ALLOC_FAILED        -0x3F80
57 /** Type mismatch, eg attempt to encrypt with an ECDSA key */
58 #define MBEDTLS_ERR_PK_TYPE_MISMATCH       -0x3F00
59 /** Bad input parameters to function. */
60 #define MBEDTLS_ERR_PK_BAD_INPUT_DATA      -0x3E80
61 /** Read/write of file failed. */
62 #define MBEDTLS_ERR_PK_FILE_IO_ERROR       -0x3E00
63 /** Unsupported key version */
64 #define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80
65 /** Invalid key tag or value. */
66 #define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT  -0x3D00
67 /** Key algorithm is unsupported (only RSA and EC are supported). */
68 #define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG      -0x3C80
69 /** Private key password can't be empty. */
70 #define MBEDTLS_ERR_PK_PASSWORD_REQUIRED   -0x3C00
71 /** Given private key password does not allow for correct decryption. */
72 #define MBEDTLS_ERR_PK_PASSWORD_MISMATCH   -0x3B80
73 /** The pubkey tag or value is invalid (only RSA and EC are supported). */
74 #define MBEDTLS_ERR_PK_INVALID_PUBKEY      -0x3B00
75 /** The algorithm tag or value is invalid. */
76 #define MBEDTLS_ERR_PK_INVALID_ALG         -0x3A80
77 /** Elliptic curve is unsupported (only NIST curves are supported). */
78 #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00
79 /** Unavailable feature, e.g. RSA disabled for RSA key. */
80 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980
81 /** The buffer contains a valid signature followed by more data. */
82 #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900
83 
84 /* MBEDTLS_ERR_PK_HW_ACCEL_FAILED is deprecated and should not be used. */
85 /** PK hardware accelerator failed. */
86 #define MBEDTLS_ERR_PK_HW_ACCEL_FAILED     -0x3880
87 
88 #ifdef __cplusplus
89 extern "C" {
90 #endif
91 
92 /**
93  * \brief          Public key types
94  */
95 typedef enum {
96     MBEDTLS_PK_NONE=0,
97     MBEDTLS_PK_RSA,
98     MBEDTLS_PK_ECKEY,
99     MBEDTLS_PK_ECKEY_DH,
100     MBEDTLS_PK_ECDSA,
101     MBEDTLS_PK_RSA_ALT,
102     MBEDTLS_PK_RSASSA_PSS,
103     MBEDTLS_PK_OPAQUE,
104 } mbedtls_pk_type_t;
105 
106 /**
107  * \brief           Options for RSASSA-PSS signature verification.
108  *                  See \c mbedtls_rsa_rsassa_pss_verify_ext()
109  */
110 typedef struct mbedtls_pk_rsassa_pss_options
111 {
112     mbedtls_md_type_t mgf1_hash_id;
113     int expected_salt_len;
114 
115 } mbedtls_pk_rsassa_pss_options;
116 
117 /**
118  * \brief           Maximum size of a signature made by mbedtls_pk_sign().
119  */
120 /* We need to set MBEDTLS_PK_SIGNATURE_MAX_SIZE to the maximum signature
121  * size among the supported signature types. Do it by starting at 0,
122  * then incrementally increasing to be large enough for each supported
123  * signature mechanism.
124  *
125  * The resulting value can be 0, for example if MBEDTLS_ECDH_C is enabled
126  * (which allows the pk module to be included) but neither MBEDTLS_ECDSA_C
127  * nor MBEDTLS_RSA_C nor any opaque signature mechanism (PSA or RSA_ALT).
128  */
129 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE 0
130 
131 #if ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_PK_RSA_ALT_SUPPORT) ) && \
132     MBEDTLS_MPI_MAX_SIZE > MBEDTLS_PK_SIGNATURE_MAX_SIZE
133 /* For RSA, the signature can be as large as the bignum module allows.
134  * For RSA_ALT, the signature size is not necessarily tied to what the
135  * bignum module can do, but in the absence of any specific setting,
136  * we use that (rsa_alt_sign_wrap in pk_wrap will check). */
137 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
138 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE MBEDTLS_MPI_MAX_SIZE
139 #endif
140 
141 #if defined(MBEDTLS_ECDSA_C) &&                                 \
142     MBEDTLS_ECDSA_MAX_LEN > MBEDTLS_PK_SIGNATURE_MAX_SIZE
143 /* For ECDSA, the ecdsa module exports a constant for the maximum
144  * signature size. */
145 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
146 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE MBEDTLS_ECDSA_MAX_LEN
147 #endif
148 
149 #if defined(MBEDTLS_USE_PSA_CRYPTO)
150 #if PSA_SIGNATURE_MAX_SIZE > MBEDTLS_PK_SIGNATURE_MAX_SIZE
151 /* PSA_SIGNATURE_MAX_SIZE is the maximum size of a signature made
152  * through the PSA API in the PSA representation. */
153 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
154 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE PSA_SIGNATURE_MAX_SIZE
155 #endif
156 
157 #if PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE + 11 > MBEDTLS_PK_SIGNATURE_MAX_SIZE
158 /* The Mbed TLS representation is different for ECDSA signatures:
159  * PSA uses the raw concatenation of r and s,
160  * whereas Mbed TLS uses the ASN.1 representation (SEQUENCE of two INTEGERs).
161  * Add the overhead of ASN.1: up to (1+2) + 2 * (1+2+1) for the
162  * types, lengths (represented by up to 2 bytes), and potential leading
163  * zeros of the INTEGERs and the SEQUENCE. */
164 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
165 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE ( PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE + 11 )
166 #endif
167 #endif /* defined(MBEDTLS_USE_PSA_CRYPTO) */
168 
169 /**
170  * \brief           Types for interfacing with the debug module
171  */
172 typedef enum
173 {
174     MBEDTLS_PK_DEBUG_NONE = 0,
175     MBEDTLS_PK_DEBUG_MPI,
176     MBEDTLS_PK_DEBUG_ECP,
177 } mbedtls_pk_debug_type;
178 
179 /**
180  * \brief           Item to send to the debug module
181  */
182 typedef struct mbedtls_pk_debug_item
183 {
184     mbedtls_pk_debug_type type;
185     const char *name;
186     void *value;
187 } mbedtls_pk_debug_item;
188 
189 /** Maximum number of item send for debugging, plus 1 */
190 #define MBEDTLS_PK_DEBUG_MAX_ITEMS 3
191 
192 /**
193  * \brief           Public key information and operations
194  */
195 typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
196 
197 /**
198  * \brief           Public key container
199  */
200 typedef struct mbedtls_pk_context
201 {
202     const mbedtls_pk_info_t *   pk_info; /**< Public key information         */
203     void *                      pk_ctx;  /**< Underlying public key context  */
204 } mbedtls_pk_context;
205 
206 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
207 /**
208  * \brief           Context for resuming operations
209  */
210 typedef struct
211 {
212     const mbedtls_pk_info_t *   pk_info; /**< Public key information         */
213     void *                      rs_ctx;  /**< Underlying restart context     */
214 } mbedtls_pk_restart_ctx;
215 #else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
216 /* Now we can declare functions that take a pointer to that */
217 typedef void mbedtls_pk_restart_ctx;
218 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
219 
220 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
221 /**
222  * \brief           Types for RSA-alt abstraction
223  */
224 typedef int (*mbedtls_pk_rsa_alt_decrypt_func)( void *ctx, int mode, size_t *olen,
225                     const unsigned char *input, unsigned char *output,
226                     size_t output_max_len );
227 typedef int (*mbedtls_pk_rsa_alt_sign_func)( void *ctx,
228                     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
229                     int mode, mbedtls_md_type_t md_alg, unsigned int hashlen,
230                     const unsigned char *hash, unsigned char *sig );
231 typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)( void *ctx );
232 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
233 
234 /**
235  * \brief           Return information associated with the given PK type
236  *
237  * \param pk_type   PK type to search for.
238  *
239  * \return          The PK info associated with the type or NULL if not found.
240  */
241 const mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type );
242 
243 /**
244  * \brief           Initialize a #mbedtls_pk_context (as NONE).
245  *
246  * \param ctx       The context to initialize.
247  *                  This must not be \c NULL.
248  */
249 void mbedtls_pk_init( mbedtls_pk_context *ctx );
250 
251 /**
252  * \brief           Free the components of a #mbedtls_pk_context.
253  *
254  * \param ctx       The context to clear. It must have been initialized.
255  *                  If this is \c NULL, this function does nothing.
256  *
257  * \note            For contexts that have been set up with
258  *                  mbedtls_pk_setup_opaque(), this does not free the underlying
259  *                  PSA key and you still need to call psa_destroy_key()
260  *                  independently if you want to destroy that key.
261  */
262 void mbedtls_pk_free( mbedtls_pk_context *ctx );
263 
264 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
265 /**
266  * \brief           Initialize a restart context
267  *
268  * \param ctx       The context to initialize.
269  *                  This must not be \c NULL.
270  */
271 void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx );
272 
273 /**
274  * \brief           Free the components of a restart context
275  *
276  * \param ctx       The context to clear. It must have been initialized.
277  *                  If this is \c NULL, this function does nothing.
278  */
279 void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx );
280 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
281 
282 /**
283  * \brief           Initialize a PK context with the information given
284  *                  and allocates the type-specific PK subcontext.
285  *
286  * \param ctx       Context to initialize. It must not have been set
287  *                  up yet (type #MBEDTLS_PK_NONE).
288  * \param info      Information to use
289  *
290  * \return          0 on success,
291  *                  MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input,
292  *                  MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
293  *
294  * \note            For contexts holding an RSA-alt key, use
295  *                  \c mbedtls_pk_setup_rsa_alt() instead.
296  */
297 int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info );
298 
299 #if defined(MBEDTLS_USE_PSA_CRYPTO)
300 /**
301  * \brief           Initialize a PK context to wrap a PSA key.
302  *
303  * \note            This function replaces mbedtls_pk_setup() for contexts
304  *                  that wrap a (possibly opaque) PSA key instead of
305  *                  storing and manipulating the key material directly.
306  *
307  * \param ctx       The context to initialize. It must be empty (type NONE).
308  * \param key       The PSA key to wrap, which must hold an ECC key pair
309  *                  (see notes below).
310  *
311  * \note            The wrapped key must remain valid as long as the
312  *                  wrapping PK context is in use, that is at least between
313  *                  the point this function is called and the point
314  *                  mbedtls_pk_free() is called on this context. The wrapped
315  *                  key might then be independently used or destroyed.
316  *
317  * \note            This function is currently only available for ECC key
318  *                  pairs (that is, ECC keys containing private key material).
319  *                  Support for other key types may be added later.
320  *
321  * \return          \c 0 on success.
322  * \return          #MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input
323  *                  (context already used, invalid key identifier).
324  * \return          #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the key is not an
325  *                  ECC key pair.
326  * \return          #MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
327  */
328 int mbedtls_pk_setup_opaque( mbedtls_pk_context *ctx,
329                              const psa_key_id_t key );
330 #endif /* MBEDTLS_USE_PSA_CRYPTO */
331 
332 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
333 /**
334  * \brief           Initialize an RSA-alt context
335  *
336  * \param ctx       Context to initialize. It must not have been set
337  *                  up yet (type #MBEDTLS_PK_NONE).
338  * \param key       RSA key pointer
339  * \param decrypt_func  Decryption function
340  * \param sign_func     Signing function
341  * \param key_len_func  Function returning key length in bytes
342  *
343  * \return          0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the
344  *                  context wasn't already initialized as RSA_ALT.
345  *
346  * \note            This function replaces \c mbedtls_pk_setup() for RSA-alt.
347  */
348 int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,
349                          mbedtls_pk_rsa_alt_decrypt_func decrypt_func,
350                          mbedtls_pk_rsa_alt_sign_func sign_func,
351                          mbedtls_pk_rsa_alt_key_len_func key_len_func );
352 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
353 
354 /**
355  * \brief           Get the size in bits of the underlying key
356  *
357  * \param ctx       The context to query. It must have been initialized.
358  *
359  * \return          Key size in bits, or 0 on error
360  */
361 size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx );
362 
363 /**
364  * \brief           Get the length in bytes of the underlying key
365  *
366  * \param ctx       The context to query. It must have been initialized.
367  *
368  * \return          Key length in bytes, or 0 on error
369  */
mbedtls_pk_get_len(const mbedtls_pk_context * ctx)370 static inline size_t mbedtls_pk_get_len( const mbedtls_pk_context *ctx )
371 {
372     return( ( mbedtls_pk_get_bitlen( ctx ) + 7 ) / 8 );
373 }
374 
375 /**
376  * \brief           Tell if a context can do the operation given by type
377  *
378  * \param ctx       The context to query. It must have been initialized.
379  * \param type      The desired type.
380  *
381  * \return          1 if the context can do operations on the given type.
382  * \return          0 if the context cannot do the operations on the given
383  *                  type. This is always the case for a context that has
384  *                  been initialized but not set up, or that has been
385  *                  cleared with mbedtls_pk_free().
386  */
387 int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type );
388 
389 /**
390  * \brief           Verify signature (including padding if relevant).
391  *
392  * \param ctx       The PK context to use. It must have been set up.
393  * \param md_alg    Hash algorithm used (see notes)
394  * \param hash      Hash of the message to sign
395  * \param hash_len  Hash length or 0 (see notes)
396  * \param sig       Signature to verify
397  * \param sig_len   Signature length
398  *
399  * \return          0 on success (signature is valid),
400  *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
401  *                  signature in sig but its length is less than \p siglen,
402  *                  or a specific error code.
403  *
404  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
405  *                  Use \c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... )
406  *                  to verify RSASSA_PSS signatures.
407  *
408  * \note            If hash_len is 0, then the length associated with md_alg
409  *                  is used instead, or an error returned if it is invalid.
410  *
411  * \note            md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0
412  */
413 int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
414                const unsigned char *hash, size_t hash_len,
415                const unsigned char *sig, size_t sig_len );
416 
417 /**
418  * \brief           Restartable version of \c mbedtls_pk_verify()
419  *
420  * \note            Performs the same job as \c mbedtls_pk_verify(), but can
421  *                  return early and restart according to the limit set with
422  *                  \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
423  *                  operations. For RSA, same as \c mbedtls_pk_verify().
424  *
425  * \param ctx       The PK context to use. It must have been set up.
426  * \param md_alg    Hash algorithm used (see notes)
427  * \param hash      Hash of the message to sign
428  * \param hash_len  Hash length or 0 (see notes)
429  * \param sig       Signature to verify
430  * \param sig_len   Signature length
431  * \param rs_ctx    Restart context (NULL to disable restart)
432  *
433  * \return          See \c mbedtls_pk_verify(), or
434  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
435  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
436  */
437 int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx,
438                mbedtls_md_type_t md_alg,
439                const unsigned char *hash, size_t hash_len,
440                const unsigned char *sig, size_t sig_len,
441                mbedtls_pk_restart_ctx *rs_ctx );
442 
443 /**
444  * \brief           Verify signature, with options.
445  *                  (Includes verification of the padding depending on type.)
446  *
447  * \param type      Signature type (inc. possible padding type) to verify
448  * \param options   Pointer to type-specific options, or NULL
449  * \param ctx       The PK context to use. It must have been set up.
450  * \param md_alg    Hash algorithm used (see notes)
451  * \param hash      Hash of the message to sign
452  * \param hash_len  Hash length or 0 (see notes)
453  * \param sig       Signature to verify
454  * \param sig_len   Signature length
455  *
456  * \return          0 on success (signature is valid),
457  *                  #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
458  *                  used for this type of signatures,
459  *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
460  *                  signature in sig but its length is less than \p siglen,
461  *                  or a specific error code.
462  *
463  * \note            If hash_len is 0, then the length associated with md_alg
464  *                  is used instead, or an error returned if it is invalid.
465  *
466  * \note            md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0
467  *
468  * \note            If type is MBEDTLS_PK_RSASSA_PSS, then options must point
469  *                  to a mbedtls_pk_rsassa_pss_options structure,
470  *                  otherwise it must be NULL.
471  */
472 int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
473                    mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
474                    const unsigned char *hash, size_t hash_len,
475                    const unsigned char *sig, size_t sig_len );
476 
477 /**
478  * \brief           Make signature, including padding if relevant.
479  *
480  * \param ctx       The PK context to use. It must have been set up
481  *                  with a private key.
482  * \param md_alg    Hash algorithm used (see notes)
483  * \param hash      Hash of the message to sign
484  * \param hash_len  Hash length or 0 (see notes)
485  * \param sig       Place to write the signature.
486  *                  It must have enough room for the signature.
487  *                  #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
488  *                  You may use a smaller buffer if it is large enough
489  *                  given the key type.
490  * \param sig_len   On successful return,
491  *                  the number of bytes written to \p sig.
492  * \param f_rng     RNG function
493  * \param p_rng     RNG parameter
494  *
495  * \return          0 on success, or a specific error code.
496  *
497  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
498  *                  There is no interface in the PK module to make RSASSA-PSS
499  *                  signatures yet.
500  *
501  * \note            If hash_len is 0, then the length associated with md_alg
502  *                  is used instead, or an error returned if it is invalid.
503  *
504  * \note            For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0.
505  *                  For ECDSA, md_alg may never be MBEDTLS_MD_NONE.
506  */
507 int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
508              const unsigned char *hash, size_t hash_len,
509              unsigned char *sig, size_t *sig_len,
510              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
511 
512 /**
513  * \brief           Restartable version of \c mbedtls_pk_sign()
514  *
515  * \note            Performs the same job as \c mbedtls_pk_sign(), but can
516  *                  return early and restart according to the limit set with
517  *                  \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
518  *                  operations. For RSA, same as \c mbedtls_pk_sign().
519  *
520  * \param ctx       The PK context to use. It must have been set up
521  *                  with a private key.
522  * \param md_alg    Hash algorithm used (see notes for mbedtls_pk_sign())
523  * \param hash      Hash of the message to sign
524  * \param hash_len  Hash length or 0 (see notes for mbedtls_pk_sign())
525  * \param sig       Place to write the signature.
526  *                  It must have enough room for the signature.
527  *                  #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
528  *                  You may use a smaller buffer if it is large enough
529  *                  given the key type.
530  * \param sig_len   On successful return,
531  *                  the number of bytes written to \p sig.
532  * \param f_rng     RNG function
533  * \param p_rng     RNG parameter
534  * \param rs_ctx    Restart context (NULL to disable restart)
535  *
536  * \return          See \c mbedtls_pk_sign().
537  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
538  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
539  */
540 int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx,
541              mbedtls_md_type_t md_alg,
542              const unsigned char *hash, size_t hash_len,
543              unsigned char *sig, size_t *sig_len,
544              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
545              mbedtls_pk_restart_ctx *rs_ctx );
546 
547 /**
548  * \brief           Decrypt message (including padding if relevant).
549  *
550  * \param ctx       The PK context to use. It must have been set up
551  *                  with a private key.
552  * \param input     Input to decrypt
553  * \param ilen      Input size
554  * \param output    Decrypted output
555  * \param olen      Decrypted message length
556  * \param osize     Size of the output buffer
557  * \param f_rng     RNG function
558  * \param p_rng     RNG parameter
559  *
560  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
561  *
562  * \return          0 on success, or a specific error code.
563  */
564 int mbedtls_pk_decrypt( mbedtls_pk_context *ctx,
565                 const unsigned char *input, size_t ilen,
566                 unsigned char *output, size_t *olen, size_t osize,
567                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
568 
569 /**
570  * \brief           Encrypt message (including padding if relevant).
571  *
572  * \param ctx       The PK context to use. It must have been set up.
573  * \param input     Message to encrypt
574  * \param ilen      Message size
575  * \param output    Encrypted output
576  * \param olen      Encrypted output length
577  * \param osize     Size of the output buffer
578  * \param f_rng     RNG function
579  * \param p_rng     RNG parameter
580  *
581  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
582  *
583  * \return          0 on success, or a specific error code.
584  */
585 int mbedtls_pk_encrypt( mbedtls_pk_context *ctx,
586                 const unsigned char *input, size_t ilen,
587                 unsigned char *output, size_t *olen, size_t osize,
588                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
589 
590 /**
591  * \brief           Check if a public-private pair of keys matches.
592  *
593  * \param pub       Context holding a public key.
594  * \param prv       Context holding a private (and public) key.
595  *
596  * \return          \c 0 on success (keys were checked and match each other).
597  * \return          #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the keys could not
598  *                  be checked - in that case they may or may not match.
599  * \return          #MBEDTLS_ERR_PK_BAD_INPUT_DATA if a context is invalid.
600  * \return          Another non-zero value if the keys do not match.
601  */
602 int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv );
603 
604 /**
605  * \brief           Export debug information
606  *
607  * \param ctx       The PK context to use. It must have been initialized.
608  * \param items     Place to write debug items
609  *
610  * \return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
611  */
612 int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items );
613 
614 /**
615  * \brief           Access the type name
616  *
617  * \param ctx       The PK context to use. It must have been initialized.
618  *
619  * \return          Type name on success, or "invalid PK"
620  */
621 const char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx );
622 
623 /**
624  * \brief           Get the key type
625  *
626  * \param ctx       The PK context to use. It must have been initialized.
627  *
628  * \return          Type on success.
629  * \return          #MBEDTLS_PK_NONE for a context that has not been set up.
630  */
631 mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );
632 
633 #if defined(MBEDTLS_RSA_C)
634 /**
635  * Quick access to an RSA context inside a PK context.
636  *
637  * \warning This function can only be used when the type of the context, as
638  * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_RSA.
639  * Ensuring that is the caller's responsibility.
640  * Alternatively, you can check whether this function returns NULL.
641  *
642  * \return The internal RSA context held by the PK context, or NULL.
643  */
mbedtls_pk_rsa(const mbedtls_pk_context pk)644 static inline mbedtls_rsa_context *mbedtls_pk_rsa( const mbedtls_pk_context pk )
645 {
646     switch( mbedtls_pk_get_type( &pk ) )
647     {
648         case MBEDTLS_PK_RSA:
649             return( (mbedtls_rsa_context *) (pk).pk_ctx );
650         default:
651             return( NULL );
652     }
653 }
654 #endif /* MBEDTLS_RSA_C */
655 
656 #if defined(MBEDTLS_ECP_C)
657 /**
658  * Quick access to an EC context inside a PK context.
659  *
660  * \warning This function can only be used when the type of the context, as
661  * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_ECKEY,
662  * #MBEDTLS_PK_ECKEY_DH, or #MBEDTLS_PK_ECDSA.
663  * Ensuring that is the caller's responsibility.
664  * Alternatively, you can check whether this function returns NULL.
665  *
666  * \return The internal EC context held by the PK context, or NULL.
667  */
mbedtls_pk_ec(const mbedtls_pk_context pk)668 static inline mbedtls_ecp_keypair *mbedtls_pk_ec( const mbedtls_pk_context pk )
669 {
670     switch( mbedtls_pk_get_type( &pk ) )
671     {
672         case MBEDTLS_PK_ECKEY:
673         case MBEDTLS_PK_ECKEY_DH:
674         case MBEDTLS_PK_ECDSA:
675             return( (mbedtls_ecp_keypair *) (pk).pk_ctx );
676         default:
677             return( NULL );
678     }
679 }
680 #endif /* MBEDTLS_ECP_C */
681 
682 #if defined(MBEDTLS_PK_PARSE_C)
683 /** \ingroup pk_module */
684 /**
685  * \brief           Parse a private key in PEM or DER format
686  *
687  * \param ctx       The PK context to fill. It must have been initialized
688  *                  but not set up.
689  * \param key       Input buffer to parse.
690  *                  The buffer must contain the input exactly, with no
691  *                  extra trailing material. For PEM, the buffer must
692  *                  contain a null-terminated string.
693  * \param keylen    Size of \b key in bytes.
694  *                  For PEM data, this includes the terminating null byte,
695  *                  so \p keylen must be equal to `strlen(key) + 1`.
696  * \param pwd       Optional password for decryption.
697  *                  Pass \c NULL if expecting a non-encrypted key.
698  *                  Pass a string of \p pwdlen bytes if expecting an encrypted
699  *                  key; a non-encrypted key will also be accepted.
700  *                  The empty password is not supported.
701  * \param pwdlen    Size of the password in bytes.
702  *                  Ignored if \p pwd is \c NULL.
703  *
704  * \note            On entry, ctx must be empty, either freshly initialised
705  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
706  *                  specific key type, check the result with mbedtls_pk_can_do().
707  *
708  * \note            The key is also checked for correctness.
709  *
710  * \return          0 if successful, or a specific PK or PEM error code
711  */
712 int mbedtls_pk_parse_key( mbedtls_pk_context *ctx,
713                   const unsigned char *key, size_t keylen,
714                   const unsigned char *pwd, size_t pwdlen );
715 
716 /** \ingroup pk_module */
717 /**
718  * \brief           Parse a public key in PEM or DER format
719  *
720  * \param ctx       The PK context to fill. It must have been initialized
721  *                  but not set up.
722  * \param key       Input buffer to parse.
723  *                  The buffer must contain the input exactly, with no
724  *                  extra trailing material. For PEM, the buffer must
725  *                  contain a null-terminated string.
726  * \param keylen    Size of \b key in bytes.
727  *                  For PEM data, this includes the terminating null byte,
728  *                  so \p keylen must be equal to `strlen(key) + 1`.
729  *
730  * \note            On entry, ctx must be empty, either freshly initialised
731  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
732  *                  specific key type, check the result with mbedtls_pk_can_do().
733  *
734  * \note            The key is also checked for correctness.
735  *
736  * \return          0 if successful, or a specific PK or PEM error code
737  */
738 int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,
739                          const unsigned char *key, size_t keylen );
740 
741 #if defined(MBEDTLS_FS_IO)
742 /** \ingroup pk_module */
743 /**
744  * \brief           Load and parse a private key
745  *
746  * \param ctx       The PK context to fill. It must have been initialized
747  *                  but not set up.
748  * \param path      filename to read the private key from
749  * \param password  Optional password to decrypt the file.
750  *                  Pass \c NULL if expecting a non-encrypted key.
751  *                  Pass a null-terminated string if expecting an encrypted
752  *                  key; a non-encrypted key will also be accepted.
753  *                  The empty password is not supported.
754  *
755  * \note            On entry, ctx must be empty, either freshly initialised
756  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
757  *                  specific key type, check the result with mbedtls_pk_can_do().
758  *
759  * \note            The key is also checked for correctness.
760  *
761  * \return          0 if successful, or a specific PK or PEM error code
762  */
763 int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
764                       const char *path, const char *password );
765 
766 /** \ingroup pk_module */
767 /**
768  * \brief           Load and parse a public key
769  *
770  * \param ctx       The PK context to fill. It must have been initialized
771  *                  but not set up.
772  * \param path      filename to read the public key from
773  *
774  * \note            On entry, ctx must be empty, either freshly initialised
775  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If
776  *                  you need a specific key type, check the result with
777  *                  mbedtls_pk_can_do().
778  *
779  * \note            The key is also checked for correctness.
780  *
781  * \return          0 if successful, or a specific PK or PEM error code
782  */
783 int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path );
784 #endif /* MBEDTLS_FS_IO */
785 #endif /* MBEDTLS_PK_PARSE_C */
786 
787 #if defined(MBEDTLS_PK_WRITE_C)
788 /**
789  * \brief           Write a private key to a PKCS#1 or SEC1 DER structure
790  *                  Note: data is written at the end of the buffer! Use the
791  *                        return value to determine where you should start
792  *                        using the buffer
793  *
794  * \param ctx       PK context which must contain a valid private key.
795  * \param buf       buffer to write to
796  * \param size      size of the buffer
797  *
798  * \return          length of data written if successful, or a specific
799  *                  error code
800  */
801 int mbedtls_pk_write_key_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
802 
803 /**
804  * \brief           Write a public key to a SubjectPublicKeyInfo DER structure
805  *                  Note: data is written at the end of the buffer! Use the
806  *                        return value to determine where you should start
807  *                        using the buffer
808  *
809  * \param ctx       PK context which must contain a valid public or private key.
810  * \param buf       buffer to write to
811  * \param size      size of the buffer
812  *
813  * \return          length of data written if successful, or a specific
814  *                  error code
815  */
816 int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
817 
818 #if defined(MBEDTLS_PEM_WRITE_C)
819 /**
820  * \brief           Write a public key to a PEM string
821  *
822  * \param ctx       PK context which must contain a valid public or private key.
823  * \param buf       Buffer to write to. The output includes a
824  *                  terminating null byte.
825  * \param size      Size of the buffer in bytes.
826  *
827  * \return          0 if successful, or a specific error code
828  */
829 int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
830 
831 /**
832  * \brief           Write a private key to a PKCS#1 or SEC1 PEM string
833  *
834  * \param ctx       PK context which must contain a valid private key.
835  * \param buf       Buffer to write to. The output includes a
836  *                  terminating null byte.
837  * \param size      Size of the buffer in bytes.
838  *
839  * \return          0 if successful, or a specific error code
840  */
841 int mbedtls_pk_write_key_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
842 #endif /* MBEDTLS_PEM_WRITE_C */
843 #endif /* MBEDTLS_PK_WRITE_C */
844 
845 /*
846  * WARNING: Low-level functions. You probably do not want to use these unless
847  *          you are certain you do ;)
848  */
849 
850 #if defined(MBEDTLS_PK_PARSE_C)
851 /**
852  * \brief           Parse a SubjectPublicKeyInfo DER structure
853  *
854  * \param p         the position in the ASN.1 data
855  * \param end       end of the buffer
856  * \param pk        The PK context to fill. It must have been initialized
857  *                  but not set up.
858  *
859  * \return          0 if successful, or a specific PK error code
860  */
861 int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,
862                         mbedtls_pk_context *pk );
863 #endif /* MBEDTLS_PK_PARSE_C */
864 
865 #if defined(MBEDTLS_PK_WRITE_C)
866 /**
867  * \brief           Write a subjectPublicKey to ASN.1 data
868  *                  Note: function works backwards in data buffer
869  *
870  * \param p         reference to current position pointer
871  * \param start     start of the buffer (for bounds-checking)
872  * \param key       PK context which must contain a valid public or private key.
873  *
874  * \return          the length written or a negative error code
875  */
876 int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,
877                      const mbedtls_pk_context *key );
878 #endif /* MBEDTLS_PK_WRITE_C */
879 
880 /*
881  * Internal module functions. You probably do not want to use these unless you
882  * know you do.
883  */
884 #if defined(MBEDTLS_FS_IO)
885 int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n );
886 #endif
887 
888 #if defined(MBEDTLS_USE_PSA_CRYPTO)
889 /**
890  * \brief           Turn an EC key into an opaque one.
891  *
892  * \warning         This is a temporary utility function for tests. It might
893  *                  change or be removed at any time without notice.
894  *
895  * \note            Only ECDSA keys are supported so far. Signing with the
896  *                  specified hash is the only allowed use of that key.
897  *
898  * \param pk        Input: the EC key to import to a PSA key.
899  *                  Output: a PK context wrapping that PSA key.
900  * \param key       Output: a PSA key identifier.
901  *                  It's the caller's responsibility to call
902  *                  psa_destroy_key() on that key identifier after calling
903  *                  mbedtls_pk_free() on the PK context.
904  * \param hash_alg  The hash algorithm to allow for use with that key.
905  *
906  * \return          \c 0 if successful.
907  * \return          An Mbed TLS error code otherwise.
908  */
909 int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk,
910                                psa_key_id_t *key,
911                                psa_algorithm_t hash_alg );
912 #endif /* MBEDTLS_USE_PSA_CRYPTO */
913 
914 #ifdef __cplusplus
915 }
916 #endif
917 
918 #endif /* MBEDTLS_PK_H */
919