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