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