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 #include "mbedtls/private_access.h"
14
15 #include "mbedtls/build_info.h"
16
17 #include "mbedtls/md.h"
18
19 #if defined(MBEDTLS_RSA_C)
20 #include "mbedtls/rsa.h"
21 #endif
22
23 #if defined(MBEDTLS_ECP_C)
24 #include "mbedtls/ecp.h"
25 #endif
26
27 #if defined(MBEDTLS_ECDSA_C)
28 #include "mbedtls/ecdsa.h"
29 #endif
30
31 #if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
32 #include "psa/crypto.h"
33 #endif
34
35 /** Memory allocation failed. */
36 #define MBEDTLS_ERR_PK_ALLOC_FAILED -0x3F80
37 /** Type mismatch, eg attempt to encrypt with an ECDSA key */
38 #define MBEDTLS_ERR_PK_TYPE_MISMATCH -0x3F00
39 /** Bad input parameters to function. */
40 #define MBEDTLS_ERR_PK_BAD_INPUT_DATA -0x3E80
41 /** Read/write of file failed. */
42 #define MBEDTLS_ERR_PK_FILE_IO_ERROR -0x3E00
43 /** Unsupported key version */
44 #define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80
45 /** Invalid key tag or value. */
46 #define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT -0x3D00
47 /** Key algorithm is unsupported (only RSA and EC are supported). */
48 #define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG -0x3C80
49 /** Private key password can't be empty. */
50 #define MBEDTLS_ERR_PK_PASSWORD_REQUIRED -0x3C00
51 /** Given private key password does not allow for correct decryption. */
52 #define MBEDTLS_ERR_PK_PASSWORD_MISMATCH -0x3B80
53 /** The pubkey tag or value is invalid (only RSA and EC are supported). */
54 #define MBEDTLS_ERR_PK_INVALID_PUBKEY -0x3B00
55 /** The algorithm tag or value is invalid. */
56 #define MBEDTLS_ERR_PK_INVALID_ALG -0x3A80
57 /** Elliptic curve is unsupported (only NIST curves are supported). */
58 #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00
59 /** Unavailable feature, e.g. RSA disabled for RSA key. */
60 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980
61 /** The buffer contains a valid signature followed by more data. */
62 #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900
63 /** The output buffer is too small. */
64 #define MBEDTLS_ERR_PK_BUFFER_TOO_SMALL -0x3880
65
66 #ifdef __cplusplus
67 extern "C" {
68 #endif
69
70 /**
71 * \brief Public key types
72 */
73 typedef enum {
74 MBEDTLS_PK_NONE=0,
75 MBEDTLS_PK_RSA,
76 MBEDTLS_PK_ECKEY,
77 MBEDTLS_PK_ECKEY_DH,
78 MBEDTLS_PK_ECDSA,
79 MBEDTLS_PK_RSA_ALT,
80 MBEDTLS_PK_RSASSA_PSS,
81 MBEDTLS_PK_OPAQUE,
82 } mbedtls_pk_type_t;
83
84 /**
85 * \brief Options for RSASSA-PSS signature verification.
86 * See \c mbedtls_rsa_rsassa_pss_verify_ext()
87 */
88 typedef struct mbedtls_pk_rsassa_pss_options {
89 /** The digest to use for MGF1 in PSS.
90 *
91 * \note When #MBEDTLS_USE_PSA_CRYPTO is enabled and #MBEDTLS_RSA_C is
92 * disabled, this must be equal to the \c md_alg argument passed
93 * to mbedtls_pk_verify_ext(). In a future version of the library,
94 * this constraint may apply whenever #MBEDTLS_USE_PSA_CRYPTO is
95 * enabled regardless of the status of #MBEDTLS_RSA_C.
96 */
97 mbedtls_md_type_t mgf1_hash_id;
98
99 /** The expected length of the salt, in bytes. This may be
100 * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length.
101 *
102 * \note When #MBEDTLS_USE_PSA_CRYPTO is enabled, only
103 * #MBEDTLS_RSA_SALT_LEN_ANY is valid. Any other value may be
104 * ignored (allowing any salt length).
105 */
106 int expected_salt_len;
107
108 } mbedtls_pk_rsassa_pss_options;
109
110 /**
111 * \brief Maximum size of a signature made by mbedtls_pk_sign().
112 */
113 /* We need to set MBEDTLS_PK_SIGNATURE_MAX_SIZE to the maximum signature
114 * size among the supported signature types. Do it by starting at 0,
115 * then incrementally increasing to be large enough for each supported
116 * signature mechanism.
117 *
118 * The resulting value can be 0, for example if MBEDTLS_ECDH_C is enabled
119 * (which allows the pk module to be included) but neither MBEDTLS_ECDSA_C
120 * nor MBEDTLS_RSA_C nor any opaque signature mechanism (PSA or RSA_ALT).
121 */
122 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE 0
123
124 #if (defined(MBEDTLS_RSA_C) || defined(MBEDTLS_PK_RSA_ALT_SUPPORT)) && \
125 MBEDTLS_MPI_MAX_SIZE > MBEDTLS_PK_SIGNATURE_MAX_SIZE
126 /* For RSA, the signature can be as large as the bignum module allows.
127 * For RSA_ALT, the signature size is not necessarily tied to what the
128 * bignum module can do, but in the absence of any specific setting,
129 * we use that (rsa_alt_sign_wrap in library/pk_wrap.h will check). */
130 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
131 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE MBEDTLS_MPI_MAX_SIZE
132 #endif
133
134 #if defined(MBEDTLS_ECDSA_C) && \
135 MBEDTLS_ECDSA_MAX_LEN > MBEDTLS_PK_SIGNATURE_MAX_SIZE
136 /* For ECDSA, the ecdsa module exports a constant for the maximum
137 * signature size. */
138 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
139 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE MBEDTLS_ECDSA_MAX_LEN
140 #endif
141
142 #if defined(MBEDTLS_USE_PSA_CRYPTO)
143 #if PSA_SIGNATURE_MAX_SIZE > MBEDTLS_PK_SIGNATURE_MAX_SIZE
144 /* PSA_SIGNATURE_MAX_SIZE is the maximum size of a signature made
145 * through the PSA API in the PSA representation. */
146 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
147 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE PSA_SIGNATURE_MAX_SIZE
148 #endif
149
150 #if PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE + 11 > MBEDTLS_PK_SIGNATURE_MAX_SIZE
151 /* The Mbed TLS representation is different for ECDSA signatures:
152 * PSA uses the raw concatenation of r and s,
153 * whereas Mbed TLS uses the ASN.1 representation (SEQUENCE of two INTEGERs).
154 * Add the overhead of ASN.1: up to (1+2) + 2 * (1+2+1) for the
155 * types, lengths (represented by up to 2 bytes), and potential leading
156 * zeros of the INTEGERs and the SEQUENCE. */
157 #undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
158 #define MBEDTLS_PK_SIGNATURE_MAX_SIZE (PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE + 11)
159 #endif
160 #endif /* defined(MBEDTLS_USE_PSA_CRYPTO) */
161
162 /* Internal helper to define which fields in the pk_context structure below
163 * should be used for EC keys: legacy ecp_keypair or the raw (PSA friendly)
164 * format. It should be noted that this only affects how data is stored, not
165 * which functions are used for various operations. The overall picture looks
166 * like this:
167 * - if USE_PSA is not defined and ECP_C is defined then use ecp_keypair data
168 * structure and legacy functions
169 * - if USE_PSA is defined and
170 * - if ECP_C then use ecp_keypair structure, convert data to a PSA friendly
171 * format and use PSA functions
172 * - if !ECP_C then use new raw data and PSA functions directly.
173 *
174 * The main reason for the "intermediate" (USE_PSA + ECP_C) above is that as long
175 * as ECP_C is defined mbedtls_pk_ec() gives the user a read/write access to the
176 * ecp_keypair structure inside the pk_context so they can modify it using
177 * ECP functions which are not under PK module's control.
178 */
179 #if defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) && \
180 !defined(MBEDTLS_ECP_C)
181 #define MBEDTLS_PK_USE_PSA_EC_DATA
182 #endif
183
184 /**
185 * \brief Types for interfacing with the debug module
186 */
187 typedef enum {
188 MBEDTLS_PK_DEBUG_NONE = 0,
189 MBEDTLS_PK_DEBUG_MPI,
190 MBEDTLS_PK_DEBUG_ECP,
191 MBEDTLS_PK_DEBUG_PSA_EC,
192 } mbedtls_pk_debug_type;
193
194 /**
195 * \brief Item to send to the debug module
196 */
197 typedef struct mbedtls_pk_debug_item {
198 mbedtls_pk_debug_type MBEDTLS_PRIVATE(type);
199 const char *MBEDTLS_PRIVATE(name);
200 void *MBEDTLS_PRIVATE(value);
201 } mbedtls_pk_debug_item;
202
203 /** Maximum number of item send for debugging, plus 1 */
204 #define MBEDTLS_PK_DEBUG_MAX_ITEMS 3
205
206 /**
207 * \brief Public key information and operations
208 *
209 * \note The library does not support custom pk info structures,
210 * only built-in structures returned by
211 * mbedtls_cipher_info_from_type().
212 */
213 typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
214
215 #define MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN \
216 PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
217 /**
218 * \brief Public key container
219 */
220 typedef struct mbedtls_pk_context {
221 const mbedtls_pk_info_t *MBEDTLS_PRIVATE(pk_info); /**< Public key information */
222 void *MBEDTLS_PRIVATE(pk_ctx); /**< Underlying public key context */
223 /* The following field is used to store the ID of a private key in the
224 * following cases:
225 * - opaque key when MBEDTLS_USE_PSA_CRYPTO is defined
226 * - normal key when MBEDTLS_PK_USE_PSA_EC_DATA is defined. In this case:
227 * - the pk_ctx above is not not used to store the private key anymore.
228 * Actually that field not populated at all in this case because also
229 * the public key will be stored in raw format as explained below
230 * - this ID is used for all private key operations (ex: sign, check
231 * key pair, key write, etc) using PSA functions
232 *
233 * Note: this private key storing solution only affects EC keys, not the
234 * other ones. The latters still use the pk_ctx to store their own
235 * context. */
236 #if defined(MBEDTLS_USE_PSA_CRYPTO)
237 mbedtls_svc_key_id_t MBEDTLS_PRIVATE(priv_id); /**< Key ID for opaque keys */
238 #endif /* MBEDTLS_USE_PSA_CRYPTO */
239 /* The following fields are meant for storing the public key in raw format
240 * which is handy for:
241 * - easily importing it into the PSA context
242 * - reducing the ECP module dependencies in the PK one.
243 *
244 * When MBEDTLS_PK_USE_PSA_EC_DATA is enabled:
245 * - the pk_ctx above is not used anymore for storing the public key
246 * inside the ecp_keypair structure
247 * - the following fields are used for all public key operations: signature
248 * verify, key pair check and key write.
249 * - For a key pair, priv_id contains the private key. For a public key,
250 * priv_id is null.
251 * Of course, when MBEDTLS_PK_USE_PSA_EC_DATA is not enabled, the legacy
252 * ecp_keypair structure is used for storing the public key and performing
253 * all the operations.
254 *
255 * Note: This new public key storing solution only works for EC keys, not
256 * other ones. The latters still use pk_ctx to store their own
257 * context.
258 */
259 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
260 uint8_t MBEDTLS_PRIVATE(pub_raw)[MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN]; /**< Raw public key */
261 size_t MBEDTLS_PRIVATE(pub_raw_len); /**< Valid bytes in "pub_raw" */
262 psa_ecc_family_t MBEDTLS_PRIVATE(ec_family); /**< EC family of pk */
263 size_t MBEDTLS_PRIVATE(ec_bits); /**< Curve's bits of pk */
264 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
265 } mbedtls_pk_context;
266
267 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
268 /**
269 * \brief Context for resuming operations
270 */
271 typedef struct {
272 const mbedtls_pk_info_t *MBEDTLS_PRIVATE(pk_info); /**< Public key information */
273 void *MBEDTLS_PRIVATE(rs_ctx); /**< Underlying restart context */
274 } mbedtls_pk_restart_ctx;
275 #else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
276 /* Now we can declare functions that take a pointer to that */
277 typedef void mbedtls_pk_restart_ctx;
278 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
279
280 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
281 /**
282 * \brief Types for RSA-alt abstraction
283 */
284 typedef int (*mbedtls_pk_rsa_alt_decrypt_func)(void *ctx, size_t *olen,
285 const unsigned char *input, unsigned char *output,
286 size_t output_max_len);
287 typedef int (*mbedtls_pk_rsa_alt_sign_func)(void *ctx,
288 int (*f_rng)(void *, unsigned char *, size_t),
289 void *p_rng,
290 mbedtls_md_type_t md_alg, unsigned int hashlen,
291 const unsigned char *hash, unsigned char *sig);
292 typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)(void *ctx);
293 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
294
295 /**
296 * \brief Return information associated with the given PK type
297 *
298 * \param pk_type PK type to search for.
299 *
300 * \return The PK info associated with the type or NULL if not found.
301 */
302 const mbedtls_pk_info_t *mbedtls_pk_info_from_type(mbedtls_pk_type_t pk_type);
303
304 /**
305 * \brief Initialize a #mbedtls_pk_context (as NONE).
306 *
307 * \param ctx The context to initialize.
308 * This must not be \c NULL.
309 */
310 void mbedtls_pk_init(mbedtls_pk_context *ctx);
311
312 /**
313 * \brief Free the components of a #mbedtls_pk_context.
314 *
315 * \param ctx The context to clear. It must have been initialized.
316 * If this is \c NULL, this function does nothing.
317 *
318 * \note For contexts that have been set up with
319 * mbedtls_pk_setup_opaque(), this does not free the underlying
320 * PSA key and you still need to call psa_destroy_key()
321 * independently if you want to destroy that key.
322 */
323 void mbedtls_pk_free(mbedtls_pk_context *ctx);
324
325 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
326 /**
327 * \brief Initialize a restart context
328 *
329 * \param ctx The context to initialize.
330 * This must not be \c NULL.
331 */
332 void mbedtls_pk_restart_init(mbedtls_pk_restart_ctx *ctx);
333
334 /**
335 * \brief Free the components of a restart context
336 *
337 * \param ctx The context to clear. It must have been initialized.
338 * If this is \c NULL, this function does nothing.
339 */
340 void mbedtls_pk_restart_free(mbedtls_pk_restart_ctx *ctx);
341 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
342
343 /**
344 * \brief Initialize a PK context with the information given
345 * and allocates the type-specific PK subcontext.
346 *
347 * \param ctx Context to initialize. It must not have been set
348 * up yet (type #MBEDTLS_PK_NONE).
349 * \param info Information to use
350 *
351 * \return 0 on success,
352 * MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input,
353 * MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
354 *
355 * \note For contexts holding an RSA-alt key, use
356 * \c mbedtls_pk_setup_rsa_alt() instead.
357 */
358 int mbedtls_pk_setup(mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info);
359
360 #if defined(MBEDTLS_USE_PSA_CRYPTO)
361 /**
362 * \brief Initialize a PK context to wrap a PSA key.
363 *
364 * \note This function replaces mbedtls_pk_setup() for contexts
365 * that wrap a (possibly opaque) PSA key instead of
366 * storing and manipulating the key material directly.
367 *
368 * \param ctx The context to initialize. It must be empty (type NONE).
369 * \param key The PSA key to wrap, which must hold an ECC or RSA key
370 * pair (see notes below).
371 *
372 * \note The wrapped key must remain valid as long as the
373 * wrapping PK context is in use, that is at least between
374 * the point this function is called and the point
375 * mbedtls_pk_free() is called on this context. The wrapped
376 * key might then be independently used or destroyed.
377 *
378 * \note This function is currently only available for ECC or RSA
379 * key pairs (that is, keys containing private key material).
380 * Support for other key types may be added later.
381 *
382 * \return \c 0 on success.
383 * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input
384 * (context already used, invalid key identifier).
385 * \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the key is not an
386 * ECC key pair.
387 * \return #MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
388 */
389 int mbedtls_pk_setup_opaque(mbedtls_pk_context *ctx,
390 const mbedtls_svc_key_id_t key);
391 #endif /* MBEDTLS_USE_PSA_CRYPTO */
392
393 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
394 /**
395 * \brief Initialize an RSA-alt context
396 *
397 * \param ctx Context to initialize. It must not have been set
398 * up yet (type #MBEDTLS_PK_NONE).
399 * \param key RSA key pointer
400 * \param decrypt_func Decryption function
401 * \param sign_func Signing function
402 * \param key_len_func Function returning key length in bytes
403 *
404 * \return 0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the
405 * context wasn't already initialized as RSA_ALT.
406 *
407 * \note This function replaces \c mbedtls_pk_setup() for RSA-alt.
408 */
409 int mbedtls_pk_setup_rsa_alt(mbedtls_pk_context *ctx, void *key,
410 mbedtls_pk_rsa_alt_decrypt_func decrypt_func,
411 mbedtls_pk_rsa_alt_sign_func sign_func,
412 mbedtls_pk_rsa_alt_key_len_func key_len_func);
413 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
414
415 /**
416 * \brief Get the size in bits of the underlying key
417 *
418 * \param ctx The context to query. It must have been initialized.
419 *
420 * \return Key size in bits, or 0 on error
421 */
422 size_t mbedtls_pk_get_bitlen(const mbedtls_pk_context *ctx);
423
424 /**
425 * \brief Get the length in bytes of the underlying key
426 *
427 * \param ctx The context to query. It must have been initialized.
428 *
429 * \return Key length in bytes, or 0 on error
430 */
mbedtls_pk_get_len(const mbedtls_pk_context * ctx)431 static inline size_t mbedtls_pk_get_len(const mbedtls_pk_context *ctx)
432 {
433 return (mbedtls_pk_get_bitlen(ctx) + 7) / 8;
434 }
435
436 /**
437 * \brief Tell if a context can do the operation given by type
438 *
439 * \param ctx The context to query. It must have been initialized.
440 * \param type The desired type.
441 *
442 * \return 1 if the context can do operations on the given type.
443 * \return 0 if the context cannot do the operations on the given
444 * type. This is always the case for a context that has
445 * been initialized but not set up, or that has been
446 * cleared with mbedtls_pk_free().
447 */
448 int mbedtls_pk_can_do(const mbedtls_pk_context *ctx, mbedtls_pk_type_t type);
449
450 #if defined(MBEDTLS_USE_PSA_CRYPTO)
451 /**
452 * \brief Tell if context can do the operation given by PSA algorithm
453 *
454 * \param ctx The context to query. It must have been initialized.
455 * \param alg PSA algorithm to check against, the following are allowed:
456 * PSA_ALG_RSA_PKCS1V15_SIGN(hash),
457 * PSA_ALG_RSA_PSS(hash),
458 * PSA_ALG_RSA_PKCS1V15_CRYPT,
459 * PSA_ALG_ECDSA(hash),
460 * PSA_ALG_ECDH, where hash is a specific hash.
461 * \param usage PSA usage flag to check against, must be composed of:
462 * PSA_KEY_USAGE_SIGN_HASH
463 * PSA_KEY_USAGE_DECRYPT
464 * PSA_KEY_USAGE_DERIVE.
465 * Context key must match all passed usage flags.
466 *
467 * \warning Since the set of allowed algorithms and usage flags may be
468 * expanded in the future, the return value \c 0 should not
469 * be taken in account for non-allowed algorithms and usage
470 * flags.
471 *
472 * \return 1 if the context can do operations on the given type.
473 * \return 0 if the context cannot do the operations on the given
474 * type, for non-allowed algorithms and usage flags, or
475 * for a context that has been initialized but not set up
476 * or that has been cleared with mbedtls_pk_free().
477 */
478 int mbedtls_pk_can_do_ext(const mbedtls_pk_context *ctx, psa_algorithm_t alg,
479 psa_key_usage_t usage);
480 #endif /* MBEDTLS_USE_PSA_CRYPTO */
481
482 #if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
483 /**
484 * \brief Determine valid PSA attributes that can be used to
485 * import a key into PSA.
486 *
487 * The attributes determined by this function are suitable
488 * for calling mbedtls_pk_import_into_psa() to create
489 * a PSA key with the same key material.
490 *
491 * The typical flow of operations involving this function is
492 * ```
493 * psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
494 * int ret = mbedtls_pk_get_psa_attributes(pk, &attributes);
495 * if (ret != 0) ...; // error handling omitted
496 * // Tweak attributes if desired
497 * psa_key_id_t key_id = 0;
498 * ret = mbedtls_pk_import_into_psa(pk, &attributes, &key_id);
499 * if (ret != 0) ...; // error handling omitted
500 * ```
501 *
502 * \note This function does not support RSA-alt contexts
503 * (set up with mbedtls_pk_setup_rsa_alt()).
504 *
505 * \param[in] pk The PK context to use. It must have been set up.
506 * It can either contain a key pair or just a public key.
507 * \param usage A single `PSA_KEY_USAGE_xxx` flag among the following:
508 * - #PSA_KEY_USAGE_DECRYPT: \p pk must contain a
509 * key pair. The output \p attributes will contain a
510 * key pair type, and the usage policy will allow
511 * #PSA_KEY_USAGE_ENCRYPT as well as
512 * #PSA_KEY_USAGE_DECRYPT.
513 * - #PSA_KEY_USAGE_DERIVE: \p pk must contain a
514 * key pair. The output \p attributes will contain a
515 * key pair type.
516 * - #PSA_KEY_USAGE_ENCRYPT: The output
517 * \p attributes will contain a public key type.
518 * - #PSA_KEY_USAGE_SIGN_HASH: \p pk must contain a
519 * key pair. The output \p attributes will contain a
520 * key pair type, and the usage policy will allow
521 * #PSA_KEY_USAGE_VERIFY_HASH as well as
522 * #PSA_KEY_USAGE_SIGN_HASH.
523 * - #PSA_KEY_USAGE_SIGN_MESSAGE: \p pk must contain a
524 * key pair. The output \p attributes will contain a
525 * key pair type, and the usage policy will allow
526 * #PSA_KEY_USAGE_VERIFY_MESSAGE as well as
527 * #PSA_KEY_USAGE_SIGN_MESSAGE.
528 * - #PSA_KEY_USAGE_VERIFY_HASH: The output
529 * \p attributes will contain a public key type.
530 * - #PSA_KEY_USAGE_VERIFY_MESSAGE: The output
531 * \p attributes will contain a public key type.
532 * \param[out] attributes
533 * On success, valid attributes to import the key into PSA.
534 * - The lifetime and key identifier are unchanged. If the
535 * attribute structure was initialized or reset before
536 * calling this function, this will result in a volatile
537 * key. Call psa_set_key_identifier() before or after this
538 * function if you wish to create a persistent key. Call
539 * psa_set_key_lifetime() before or after this function if
540 * you wish to import the key in a secure element.
541 * - The key type and bit-size are determined by the contents
542 * of the PK context. If the PK context contains a key
543 * pair, the key type can be either a key pair type or
544 * the corresponding public key type, depending on
545 * \p usage. If the PK context contains a public key,
546 * the key type is a public key type.
547 * - The key's policy is determined by the key type and
548 * the \p usage parameter. The usage always allows
549 * \p usage, exporting and copying the key, and
550 * possibly other permissions as documented for the
551 * \p usage parameter.
552 * The permitted algorithm policy is determined as follows
553 * based on the #mbedtls_pk_type_t type of \p pk,
554 * the chosen \p usage and other factors:
555 * - #MBEDTLS_PK_RSA whose underlying
556 * #mbedtls_rsa_context has the padding mode
557 * #MBEDTLS_RSA_PKCS_V15:
558 * #PSA_ALG_RSA_PKCS1V15_SIGN(#PSA_ALG_ANY_HASH)
559 * if \p usage is SIGN/VERIFY, and
560 * #PSA_ALG_RSA_PKCS1V15_CRYPT
561 * if \p usage is ENCRYPT/DECRYPT.
562 * - #MBEDTLS_PK_RSA whose underlying
563 * #mbedtls_rsa_context has the padding mode
564 * #MBEDTLS_RSA_PKCS_V21 and the digest type
565 * corresponding to the PSA algorithm \c hash:
566 * #PSA_ALG_RSA_PSS_ANY_SALT(#PSA_ALG_ANY_HASH)
567 * if \p usage is SIGN/VERIFY, and
568 * #PSA_ALG_RSA_OAEP(\c hash)
569 * if \p usage is ENCRYPT/DECRYPT.
570 * - #MBEDTLS_PK_RSA_ALT: not supported.
571 * - #MBEDTLS_PK_ECDSA or #MBEDTLS_PK_ECKEY
572 * if \p usage is SIGN/VERIFY:
573 * #PSA_ALG_DETERMINISTIC_ECDSA(#PSA_ALG_ANY_HASH)
574 * if #MBEDTLS_ECDSA_DETERMINISTIC is enabled,
575 * otherwise #PSA_ALG_ECDSA(#PSA_ALG_ANY_HASH).
576 * - #MBEDTLS_PK_ECKEY_DH or #MBEDTLS_PK_ECKEY
577 * if \p usage is DERIVE:
578 * #PSA_ALG_ECDH.
579 * - #MBEDTLS_PK_OPAQUE: same as the primary algorithm
580 * set for the underlying PSA key, except that
581 * sign/decrypt flags are removed if the type is
582 * set to a public key type.
583 * The underlying key must allow \p usage.
584 * Note that the enrollment algorithm set with
585 * psa_set_key_enrollment_algorithm() is not copied.
586 *
587 * \return 0 on success.
588 * #MBEDTLS_ERR_PK_TYPE_MISMATCH if \p pk does not contain
589 * a key of the type identified in \p attributes.
590 * Another error code on other failures.
591 */
592 int mbedtls_pk_get_psa_attributes(const mbedtls_pk_context *pk,
593 psa_key_usage_t usage,
594 psa_key_attributes_t *attributes);
595
596 /**
597 * \brief Import a key into the PSA key store.
598 *
599 * This function is equivalent to calling psa_import_key()
600 * with the key material from \p pk.
601 *
602 * The typical way to use this function is:
603 * -# Call mbedtls_pk_get_psa_attributes() to obtain
604 * attributes for the given key.
605 * -# If desired, modify the attributes, for example:
606 * - To create a persistent key, call
607 * psa_set_key_identifier() and optionally
608 * psa_set_key_lifetime().
609 * - To import only the public part of a key pair:
610 *
611 * psa_set_key_type(&attributes,
612 * PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(
613 * psa_get_key_type(&attributes)));
614 * - Restrict the key usage if desired.
615 * -# Call mbedtls_pk_import_into_psa().
616 *
617 * \note This function does not support RSA-alt contexts
618 * (set up with mbedtls_pk_setup_rsa_alt()).
619 *
620 * \param[in] pk The PK context to use. It must have been set up.
621 * It can either contain a key pair or just a public key.
622 * \param[in] attributes
623 * The attributes to use for the new key. They must be
624 * compatible with \p pk. In particular, the key type
625 * must match the content of \p pk.
626 * If \p pk contains a key pair, the key type in
627 * attributes can be either the key pair type or the
628 * corresponding public key type (to import only the
629 * public part).
630 * \param[out] key_id
631 * On success, the identifier of the newly created key.
632 * On error, this is #MBEDTLS_SVC_KEY_ID_INIT.
633 *
634 * \return 0 on success.
635 * #MBEDTLS_ERR_PK_TYPE_MISMATCH if \p pk does not contain
636 * a key of the type identified in \p attributes.
637 * Another error code on other failures.
638 */
639 int mbedtls_pk_import_into_psa(const mbedtls_pk_context *pk,
640 const psa_key_attributes_t *attributes,
641 mbedtls_svc_key_id_t *key_id);
642
643 /**
644 * \brief Create a PK context starting from a key stored in PSA.
645 * This key:
646 * - must be exportable and
647 * - must be an RSA or EC key pair or public key (FFDH is not supported in PK).
648 *
649 * The resulting PK object will be a transparent type:
650 * - #MBEDTLS_PK_RSA for RSA keys or
651 * - #MBEDTLS_PK_ECKEY for EC keys.
652 *
653 * Once this functions returns the PK object will be completely
654 * independent from the original PSA key that it was generated
655 * from.
656 * Calling mbedtls_pk_sign(), mbedtls_pk_verify(),
657 * mbedtls_pk_encrypt(), mbedtls_pk_decrypt() on the resulting
658 * PK context will perform the corresponding algorithm for that
659 * PK context type.
660 * * For ECDSA, the choice of deterministic vs randomized will
661 * be based on the compile-time setting #MBEDTLS_ECDSA_DETERMINISTIC.
662 * * For an RSA key, the output PK context will allow both
663 * encrypt/decrypt and sign/verify regardless of the original
664 * key's policy.
665 * The original key's policy determines the output key's padding
666 * mode: PCKS1 v2.1 is set if the PSA key policy is OAEP or PSS,
667 * otherwise PKCS1 v1.5 is set.
668 *
669 * \param key_id The key identifier of the key stored in PSA.
670 * \param pk The PK context that will be filled. It must be initialized,
671 * but not set up.
672 *
673 * \return 0 on success.
674 * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA in case the provided input
675 * parameters are not correct.
676 */
677 int mbedtls_pk_copy_from_psa(mbedtls_svc_key_id_t key_id, mbedtls_pk_context *pk);
678
679 /**
680 * \brief Create a PK context for the public key of a PSA key.
681 *
682 * The key must be an RSA or ECC key. It can be either a
683 * public key or a key pair, and only the public key is copied.
684 * The resulting PK object will be a transparent type:
685 * - #MBEDTLS_PK_RSA for RSA keys or
686 * - #MBEDTLS_PK_ECKEY for EC keys.
687 *
688 * Once this functions returns the PK object will be completely
689 * independent from the original PSA key that it was generated
690 * from.
691 * Calling mbedtls_pk_verify() or
692 * mbedtls_pk_encrypt() on the resulting
693 * PK context will perform the corresponding algorithm for that
694 * PK context type.
695 *
696 * For an RSA key, the output PK context will allow both
697 * encrypt and verify regardless of the original key's policy.
698 * The original key's policy determines the output key's padding
699 * mode: PCKS1 v2.1 is set if the PSA key policy is OAEP or PSS,
700 * otherwise PKCS1 v1.5 is set.
701 *
702 * \param key_id The key identifier of the key stored in PSA.
703 * \param pk The PK context that will be filled. It must be initialized,
704 * but not set up.
705 *
706 * \return 0 on success.
707 * \return MBEDTLS_ERR_PK_BAD_INPUT_DATA in case the provided input
708 * parameters are not correct.
709 */
710 int mbedtls_pk_copy_public_from_psa(mbedtls_svc_key_id_t key_id, mbedtls_pk_context *pk);
711 #endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
712
713 /**
714 * \brief Verify signature (including padding if relevant).
715 *
716 * \param ctx The PK context to use. It must have been set up.
717 * \param md_alg Hash algorithm used.
718 * This can be #MBEDTLS_MD_NONE if the signature algorithm
719 * does not rely on a hash algorithm (non-deterministic
720 * ECDSA, RSA PKCS#1 v1.5).
721 * For PKCS#1 v1.5, if \p md_alg is #MBEDTLS_MD_NONE, then
722 * \p hash is the DigestInfo structure used by RFC 8017
723 * §9.2 steps 3–6. If \p md_alg is a valid hash
724 * algorithm then \p hash is the digest itself, and this
725 * function calculates the DigestInfo encoding internally.
726 * \param hash Hash of the message to sign
727 * \param hash_len Hash length
728 * \param sig Signature to verify
729 * \param sig_len Signature length
730 *
731 * \note For keys of type #MBEDTLS_PK_RSA, the signature algorithm is
732 * either PKCS#1 v1.5 or PSS (accepting any salt length),
733 * depending on the padding mode in the underlying RSA context.
734 * For a pk object constructed by parsing, this is PKCS#1 v1.5
735 * by default. Use mbedtls_pk_verify_ext() to explicitly select
736 * a different algorithm.
737 *
738 * \return 0 on success (signature is valid),
739 * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
740 * signature in \p sig but its length is less than \p sig_len,
741 * or a specific error code.
742 */
743 int mbedtls_pk_verify(mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
744 const unsigned char *hash, size_t hash_len,
745 const unsigned char *sig, size_t sig_len);
746
747 /**
748 * \brief Restartable version of \c mbedtls_pk_verify()
749 *
750 * \note Performs the same job as \c mbedtls_pk_verify(), but can
751 * return early and restart according to the limit set with
752 * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
753 * operations. For RSA, same as \c mbedtls_pk_verify().
754 *
755 * \param ctx The PK context to use. It must have been set up.
756 * \param md_alg Hash algorithm used (see notes)
757 * \param hash Hash of the message to sign
758 * \param hash_len Hash length or 0 (see notes)
759 * \param sig Signature to verify
760 * \param sig_len Signature length
761 * \param rs_ctx Restart context (NULL to disable restart)
762 *
763 * \return See \c mbedtls_pk_verify(), or
764 * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
765 * operations was reached: see \c mbedtls_ecp_set_max_ops().
766 */
767 int mbedtls_pk_verify_restartable(mbedtls_pk_context *ctx,
768 mbedtls_md_type_t md_alg,
769 const unsigned char *hash, size_t hash_len,
770 const unsigned char *sig, size_t sig_len,
771 mbedtls_pk_restart_ctx *rs_ctx);
772
773 /**
774 * \brief Verify signature, with options.
775 * (Includes verification of the padding depending on type.)
776 *
777 * \param type Signature type (inc. possible padding type) to verify
778 * \param options Pointer to type-specific options, or NULL
779 * \param ctx The PK context to use. It must have been set up.
780 * \param md_alg Hash algorithm used (see notes)
781 * \param hash Hash of the message to sign
782 * \param hash_len Hash length or 0 (see notes)
783 * \param sig Signature to verify
784 * \param sig_len Signature length
785 *
786 * \return 0 on success (signature is valid),
787 * #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
788 * used for this type of signatures,
789 * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
790 * signature in \p sig but its length is less than \p sig_len,
791 * or a specific error code.
792 *
793 * \note If hash_len is 0, then the length associated with md_alg
794 * is used instead, or an error returned if it is invalid.
795 *
796 * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0
797 *
798 * \note If type is MBEDTLS_PK_RSASSA_PSS, then options must point
799 * to a mbedtls_pk_rsassa_pss_options structure,
800 * otherwise it must be NULL. Note that if
801 * #MBEDTLS_USE_PSA_CRYPTO is defined, the salt length is not
802 * verified as PSA_ALG_RSA_PSS_ANY_SALT is used.
803 */
804 int mbedtls_pk_verify_ext(mbedtls_pk_type_t type, const void *options,
805 mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
806 const unsigned char *hash, size_t hash_len,
807 const unsigned char *sig, size_t sig_len);
808
809 /**
810 * \brief Make signature, including padding if relevant.
811 *
812 * \param ctx The PK context to use. It must have been set up
813 * with a private key.
814 * \param md_alg Hash algorithm used (see notes)
815 * \param hash Hash of the message to sign
816 * \param hash_len Hash length
817 * \param sig Place to write the signature.
818 * It must have enough room for the signature.
819 * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
820 * You may use a smaller buffer if it is large enough
821 * given the key type.
822 * \param sig_size The size of the \p sig buffer in bytes.
823 * \param sig_len On successful return,
824 * the number of bytes written to \p sig.
825 * \param f_rng RNG function, must not be \c NULL.
826 * \param p_rng RNG parameter
827 *
828 * \note For keys of type #MBEDTLS_PK_RSA, the signature algorithm is
829 * either PKCS#1 v1.5 or PSS (using the largest possible salt
830 * length up to the hash length), depending on the padding mode
831 * in the underlying RSA context. For a pk object constructed
832 * by parsing, this is PKCS#1 v1.5 by default. Use
833 * mbedtls_pk_verify_ext() to explicitly select a different
834 * algorithm.
835 *
836 * \return 0 on success, or a specific error code.
837 *
838 * \note For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0.
839 * For ECDSA, md_alg may never be MBEDTLS_MD_NONE.
840 */
841 int mbedtls_pk_sign(mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
842 const unsigned char *hash, size_t hash_len,
843 unsigned char *sig, size_t sig_size, size_t *sig_len,
844 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
845
846 /**
847 * \brief Make signature given a signature type.
848 *
849 * \param pk_type Signature type.
850 * \param ctx The PK context to use. It must have been set up
851 * with a private key.
852 * \param md_alg Hash algorithm used (see notes)
853 * \param hash Hash of the message to sign
854 * \param hash_len Hash length
855 * \param sig Place to write the signature.
856 * It must have enough room for the signature.
857 * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
858 * You may use a smaller buffer if it is large enough
859 * given the key type.
860 * \param sig_size The size of the \p sig buffer in bytes.
861 * \param sig_len On successful return,
862 * the number of bytes written to \p sig.
863 * \param f_rng RNG function, must not be \c NULL.
864 * \param p_rng RNG parameter
865 *
866 * \return 0 on success, or a specific error code.
867 *
868 * \note When \p pk_type is #MBEDTLS_PK_RSASSA_PSS,
869 * see #PSA_ALG_RSA_PSS for a description of PSS options used.
870 *
871 * \note For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0.
872 * For ECDSA, md_alg may never be MBEDTLS_MD_NONE.
873 *
874 */
875 int mbedtls_pk_sign_ext(mbedtls_pk_type_t pk_type,
876 mbedtls_pk_context *ctx,
877 mbedtls_md_type_t md_alg,
878 const unsigned char *hash, size_t hash_len,
879 unsigned char *sig, size_t sig_size, size_t *sig_len,
880 int (*f_rng)(void *, unsigned char *, size_t),
881 void *p_rng);
882
883 /**
884 * \brief Restartable version of \c mbedtls_pk_sign()
885 *
886 * \note Performs the same job as \c mbedtls_pk_sign(), but can
887 * return early and restart according to the limit set with
888 * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
889 * operations. For RSA, same as \c mbedtls_pk_sign().
890 *
891 * \param ctx The PK context to use. It must have been set up
892 * with a private key.
893 * \param md_alg Hash algorithm used (see notes for mbedtls_pk_sign())
894 * \param hash Hash of the message to sign
895 * \param hash_len Hash length
896 * \param sig Place to write the signature.
897 * It must have enough room for the signature.
898 * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
899 * You may use a smaller buffer if it is large enough
900 * given the key type.
901 * \param sig_size The size of the \p sig buffer in bytes.
902 * \param sig_len On successful return,
903 * the number of bytes written to \p sig.
904 * \param f_rng RNG function, must not be \c NULL.
905 * \param p_rng RNG parameter
906 * \param rs_ctx Restart context (NULL to disable restart)
907 *
908 * \return See \c mbedtls_pk_sign().
909 * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
910 * operations was reached: see \c mbedtls_ecp_set_max_ops().
911 */
912 int mbedtls_pk_sign_restartable(mbedtls_pk_context *ctx,
913 mbedtls_md_type_t md_alg,
914 const unsigned char *hash, size_t hash_len,
915 unsigned char *sig, size_t sig_size, size_t *sig_len,
916 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
917 mbedtls_pk_restart_ctx *rs_ctx);
918
919 /**
920 * \brief Decrypt message (including padding if relevant).
921 *
922 * \param ctx The PK context to use. It must have been set up
923 * with a private key.
924 * \param input Input to decrypt
925 * \param ilen Input size
926 * \param output Decrypted output
927 * \param olen Decrypted message length
928 * \param osize Size of the output buffer
929 * \param f_rng RNG function, must not be \c NULL.
930 * \param p_rng RNG parameter
931 *
932 * \note For keys of type #MBEDTLS_PK_RSA, the signature algorithm is
933 * either PKCS#1 v1.5 or OAEP, depending on the padding mode in
934 * the underlying RSA context. For a pk object constructed by
935 * parsing, this is PKCS#1 v1.5 by default.
936 *
937 * \return 0 on success, or a specific error code.
938 */
939 int mbedtls_pk_decrypt(mbedtls_pk_context *ctx,
940 const unsigned char *input, size_t ilen,
941 unsigned char *output, size_t *olen, size_t osize,
942 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
943
944 /**
945 * \brief Encrypt message (including padding if relevant).
946 *
947 * \param ctx The PK context to use. It must have been set up.
948 * \param input Message to encrypt
949 * \param ilen Message size
950 * \param output Encrypted output
951 * \param olen Encrypted output length
952 * \param osize Size of the output buffer
953 * \param f_rng RNG function, must not be \c NULL.
954 * \param p_rng RNG parameter
955 *
956 * \note For keys of type #MBEDTLS_PK_RSA, the signature algorithm is
957 * either PKCS#1 v1.5 or OAEP, depending on the padding mode in
958 * the underlying RSA context. For a pk object constructed by
959 * parsing, this is PKCS#1 v1.5 by default.
960 *
961 * \note \p f_rng is used for padding generation.
962 *
963 * \return 0 on success, or a specific error code.
964 */
965 int mbedtls_pk_encrypt(mbedtls_pk_context *ctx,
966 const unsigned char *input, size_t ilen,
967 unsigned char *output, size_t *olen, size_t osize,
968 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
969
970 /**
971 * \brief Check if a public-private pair of keys matches.
972 *
973 * \param pub Context holding a public key.
974 * \param prv Context holding a private (and public) key.
975 * \param f_rng RNG function, must not be \c NULL.
976 * \param p_rng RNG parameter
977 *
978 * \return \c 0 on success (keys were checked and match each other).
979 * \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the keys could not
980 * be checked - in that case they may or may not match.
981 * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA if a context is invalid.
982 * \return Another non-zero value if the keys do not match.
983 */
984 int mbedtls_pk_check_pair(const mbedtls_pk_context *pub,
985 const mbedtls_pk_context *prv,
986 int (*f_rng)(void *, unsigned char *, size_t),
987 void *p_rng);
988
989 /**
990 * \brief Export debug information
991 *
992 * \param ctx The PK context to use. It must have been initialized.
993 * \param items Place to write debug items
994 *
995 * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
996 */
997 int mbedtls_pk_debug(const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items);
998
999 /**
1000 * \brief Access the type name
1001 *
1002 * \param ctx The PK context to use. It must have been initialized.
1003 *
1004 * \return Type name on success, or "invalid PK"
1005 */
1006 const char *mbedtls_pk_get_name(const mbedtls_pk_context *ctx);
1007
1008 /**
1009 * \brief Get the key type
1010 *
1011 * \param ctx The PK context to use. It must have been initialized.
1012 *
1013 * \return Type on success.
1014 * \return #MBEDTLS_PK_NONE for a context that has not been set up.
1015 */
1016 mbedtls_pk_type_t mbedtls_pk_get_type(const mbedtls_pk_context *ctx);
1017
1018 #if defined(MBEDTLS_RSA_C)
1019 /**
1020 * Quick access to an RSA context inside a PK context.
1021 *
1022 * \warning This function can only be used when the type of the context, as
1023 * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_RSA.
1024 * Ensuring that is the caller's responsibility.
1025 * Alternatively, you can check whether this function returns NULL.
1026 *
1027 * \return The internal RSA context held by the PK context, or NULL.
1028 */
mbedtls_pk_rsa(const mbedtls_pk_context pk)1029 static inline mbedtls_rsa_context *mbedtls_pk_rsa(const mbedtls_pk_context pk)
1030 {
1031 switch (mbedtls_pk_get_type(&pk)) {
1032 case MBEDTLS_PK_RSA:
1033 return (mbedtls_rsa_context *) (pk).MBEDTLS_PRIVATE(pk_ctx);
1034 default:
1035 return NULL;
1036 }
1037 }
1038 #endif /* MBEDTLS_RSA_C */
1039
1040 #if defined(MBEDTLS_ECP_C)
1041 /**
1042 * Quick access to an EC context inside a PK context.
1043 *
1044 * \warning This function can only be used when the type of the context, as
1045 * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_ECKEY,
1046 * #MBEDTLS_PK_ECKEY_DH, or #MBEDTLS_PK_ECDSA.
1047 * Ensuring that is the caller's responsibility.
1048 * Alternatively, you can check whether this function returns NULL.
1049 *
1050 * \return The internal EC context held by the PK context, or NULL.
1051 */
mbedtls_pk_ec(const mbedtls_pk_context pk)1052 static inline mbedtls_ecp_keypair *mbedtls_pk_ec(const mbedtls_pk_context pk)
1053 {
1054 switch (mbedtls_pk_get_type(&pk)) {
1055 case MBEDTLS_PK_ECKEY:
1056 case MBEDTLS_PK_ECKEY_DH:
1057 case MBEDTLS_PK_ECDSA:
1058 return (mbedtls_ecp_keypair *) (pk).MBEDTLS_PRIVATE(pk_ctx);
1059 default:
1060 return NULL;
1061 }
1062 }
1063 #endif /* MBEDTLS_ECP_C */
1064
1065 #if defined(MBEDTLS_PK_PARSE_C)
1066 /** \ingroup pk_module */
1067 /**
1068 * \brief Parse a private key in PEM or DER format
1069 *
1070 * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
1071 * subsystem must have been initialized by calling
1072 * psa_crypto_init() before calling this function.
1073 *
1074 * \param ctx The PK context to fill. It must have been initialized
1075 * but not set up.
1076 * \param key Input buffer to parse.
1077 * The buffer must contain the input exactly, with no
1078 * extra trailing material. For PEM, the buffer must
1079 * contain a null-terminated string.
1080 * \param keylen Size of \b key in bytes.
1081 * For PEM data, this includes the terminating null byte,
1082 * so \p keylen must be equal to `strlen(key) + 1`.
1083 * \param pwd Optional password for decryption.
1084 * Pass \c NULL if expecting a non-encrypted key.
1085 * Pass a string of \p pwdlen bytes if expecting an encrypted
1086 * key; a non-encrypted key will also be accepted.
1087 * The empty password is not supported.
1088 * \param pwdlen Size of the password in bytes.
1089 * Ignored if \p pwd is \c NULL.
1090 * \param f_rng RNG function, must not be \c NULL. Used for blinding.
1091 * \param p_rng RNG parameter
1092 *
1093 * \note On entry, ctx must be empty, either freshly initialised
1094 * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
1095 * specific key type, check the result with mbedtls_pk_can_do().
1096 *
1097 * \note The key is also checked for correctness.
1098 *
1099 * \return 0 if successful, or a specific PK or PEM error code
1100 */
1101 int mbedtls_pk_parse_key(mbedtls_pk_context *ctx,
1102 const unsigned char *key, size_t keylen,
1103 const unsigned char *pwd, size_t pwdlen,
1104 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
1105
1106 /** \ingroup pk_module */
1107 /**
1108 * \brief Parse a public key in PEM or DER format
1109 *
1110 * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
1111 * subsystem must have been initialized by calling
1112 * psa_crypto_init() before calling this function.
1113 *
1114 * \param ctx The PK context to fill. It must have been initialized
1115 * but not set up.
1116 * \param key Input buffer to parse.
1117 * The buffer must contain the input exactly, with no
1118 * extra trailing material. For PEM, the buffer must
1119 * contain a null-terminated string.
1120 * \param keylen Size of \b key in bytes.
1121 * For PEM data, this includes the terminating null byte,
1122 * so \p keylen must be equal to `strlen(key) + 1`.
1123 *
1124 * \note On entry, ctx must be empty, either freshly initialised
1125 * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
1126 * specific key type, check the result with mbedtls_pk_can_do().
1127 *
1128 * \note For compressed points, see #MBEDTLS_ECP_PF_COMPRESSED for
1129 * limitations.
1130 *
1131 * \note The key is also checked for correctness.
1132 *
1133 * \return 0 if successful, or a specific PK or PEM error code
1134 */
1135 int mbedtls_pk_parse_public_key(mbedtls_pk_context *ctx,
1136 const unsigned char *key, size_t keylen);
1137
1138 #if defined(MBEDTLS_FS_IO)
1139 /** \ingroup pk_module */
1140 /**
1141 * \brief Load and parse a private key
1142 *
1143 * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
1144 * subsystem must have been initialized by calling
1145 * psa_crypto_init() before calling this function.
1146 *
1147 * \param ctx The PK context to fill. It must have been initialized
1148 * but not set up.
1149 * \param path filename to read the private key from
1150 * \param password Optional password to decrypt the file.
1151 * Pass \c NULL if expecting a non-encrypted key.
1152 * Pass a null-terminated string if expecting an encrypted
1153 * key; a non-encrypted key will also be accepted.
1154 * The empty password is not supported.
1155 * \param f_rng RNG function, must not be \c NULL. Used for blinding.
1156 * \param p_rng RNG parameter
1157 *
1158 * \note On entry, ctx must be empty, either freshly initialised
1159 * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
1160 * specific key type, check the result with mbedtls_pk_can_do().
1161 *
1162 * \note The key is also checked for correctness.
1163 *
1164 * \return 0 if successful, or a specific PK or PEM error code
1165 */
1166 int mbedtls_pk_parse_keyfile(mbedtls_pk_context *ctx,
1167 const char *path, const char *password,
1168 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
1169
1170 /** \ingroup pk_module */
1171 /**
1172 * \brief Load and parse a public key
1173 *
1174 * \param ctx The PK context to fill. It must have been initialized
1175 * but not set up.
1176 * \param path filename to read the public key from
1177 *
1178 * \note On entry, ctx must be empty, either freshly initialised
1179 * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If
1180 * you need a specific key type, check the result with
1181 * mbedtls_pk_can_do().
1182 *
1183 * \note The key is also checked for correctness.
1184 *
1185 * \return 0 if successful, or a specific PK or PEM error code
1186 */
1187 int mbedtls_pk_parse_public_keyfile(mbedtls_pk_context *ctx, const char *path);
1188 #endif /* MBEDTLS_FS_IO */
1189 #endif /* MBEDTLS_PK_PARSE_C */
1190
1191 #if defined(MBEDTLS_PK_WRITE_C)
1192 /**
1193 * \brief Write a private key to a PKCS#1 or SEC1 DER structure
1194 * Note: data is written at the end of the buffer! Use the
1195 * return value to determine where you should start
1196 * using the buffer
1197 *
1198 * \param ctx PK context which must contain a valid private key.
1199 * \param buf buffer to write to
1200 * \param size size of the buffer
1201 *
1202 * \return length of data written if successful, or a specific
1203 * error code
1204 */
1205 int mbedtls_pk_write_key_der(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1206
1207 /**
1208 * \brief Write a public key to a SubjectPublicKeyInfo DER structure
1209 * Note: data is written at the end of the buffer! Use the
1210 * return value to determine where you should start
1211 * using the buffer
1212 *
1213 * \param ctx PK context which must contain a valid public or private key.
1214 * \param buf buffer to write to
1215 * \param size size of the buffer
1216 *
1217 * \return length of data written if successful, or a specific
1218 * error code
1219 */
1220 int mbedtls_pk_write_pubkey_der(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1221
1222 #if defined(MBEDTLS_PEM_WRITE_C)
1223 /**
1224 * \brief Write a public key to a PEM string
1225 *
1226 * \param ctx PK context which must contain a valid public or private key.
1227 * \param buf Buffer to write to. The output includes a
1228 * terminating null byte.
1229 * \param size Size of the buffer in bytes.
1230 *
1231 * \return 0 if successful, or a specific error code
1232 */
1233 int mbedtls_pk_write_pubkey_pem(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1234
1235 /**
1236 * \brief Write a private key to a PKCS#1 or SEC1 PEM string
1237 *
1238 * \param ctx PK context which must contain a valid private key.
1239 * \param buf Buffer to write to. The output includes a
1240 * terminating null byte.
1241 * \param size Size of the buffer in bytes.
1242 *
1243 * \return 0 if successful, or a specific error code
1244 */
1245 int mbedtls_pk_write_key_pem(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1246 #endif /* MBEDTLS_PEM_WRITE_C */
1247 #endif /* MBEDTLS_PK_WRITE_C */
1248
1249 /*
1250 * WARNING: Low-level functions. You probably do not want to use these unless
1251 * you are certain you do ;)
1252 */
1253
1254 #if defined(MBEDTLS_PK_PARSE_C)
1255 /**
1256 * \brief Parse a SubjectPublicKeyInfo DER structure
1257 *
1258 * \param p the position in the ASN.1 data
1259 * \param end end of the buffer
1260 * \param pk The PK context to fill. It must have been initialized
1261 * but not set up.
1262 *
1263 * \return 0 if successful, or a specific PK error code
1264 */
1265 int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
1266 mbedtls_pk_context *pk);
1267 #endif /* MBEDTLS_PK_PARSE_C */
1268
1269 #if defined(MBEDTLS_PK_WRITE_C)
1270 /**
1271 * \brief Write a subjectPublicKey to ASN.1 data
1272 * Note: function works backwards in data buffer
1273 *
1274 * \param p reference to current position pointer
1275 * \param start start of the buffer (for bounds-checking)
1276 * \param key PK context which must contain a valid public or private key.
1277 *
1278 * \return the length written or a negative error code
1279 */
1280 int mbedtls_pk_write_pubkey(unsigned char **p, unsigned char *start,
1281 const mbedtls_pk_context *key);
1282 #endif /* MBEDTLS_PK_WRITE_C */
1283
1284 #ifdef __cplusplus
1285 }
1286 #endif
1287
1288 #endif /* MBEDTLS_PK_H */
1289