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