Coverage Report

Created: 2026-10-17 06:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/mbedtls-3.6.6/include/mbedtls/pk.h
Line
Count
Source
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
0
#define MBEDTLS_ERR_PK_ALLOC_FAILED        -0x3F80
37
/** Type mismatch, eg attempt to encrypt with an ECDSA key */
38
0
#define MBEDTLS_ERR_PK_TYPE_MISMATCH       -0x3F00
39
/** Bad input parameters to function. */
40
0
#define MBEDTLS_ERR_PK_BAD_INPUT_DATA      -0x3E80
41
/** Read/write of file failed. */
42
0
#define MBEDTLS_ERR_PK_FILE_IO_ERROR       -0x3E00
43
/** Unsupported key version */
44
0
#define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80
45
/** Invalid key tag or value. */
46
0
#define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT  -0x3D00
47
/** Key algorithm is unsupported (only RSA and EC are supported). */
48
0
#define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG      -0x3C80
49
/** Private key password can't be empty. */
50
0
#define MBEDTLS_ERR_PK_PASSWORD_REQUIRED   -0x3C00
51
/** Given private key password does not allow for correct decryption. */
52
0
#define MBEDTLS_ERR_PK_PASSWORD_MISMATCH   -0x3B80
53
/** The pubkey tag or value is invalid (only RSA and EC are supported). */
54
0
#define MBEDTLS_ERR_PK_INVALID_PUBKEY      -0x3B00
55
/** The algorithm tag or value is invalid. */
56
0
#define MBEDTLS_ERR_PK_INVALID_ALG         -0x3A80
57
/** Elliptic curve is unsupported (only NIST curves are supported). */
58
0
#define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00
59
/** Unavailable feature, e.g. RSA disabled for RSA key. */
60
0
#define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980
61
/** The buffer contains a valid signature followed by more data. */
62
0
#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900
63
/** The output buffer is too small. */
64
0
#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
0
#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
    /** 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
 */
274
typedef 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 */
280
typedef 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
 */
287
typedef 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);
290
typedef 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);
295
typedef 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
 */
305
const 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
 */
313
void 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
 */
326
void 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
 */
335
void 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
 */
343
void 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
 */
361
int 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
 */
400
int 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
 */
420
int 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
 */
433
size_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
 */
442
static inline size_t mbedtls_pk_get_len(const mbedtls_pk_context *ctx)
443
0
{
444
0
    return (mbedtls_pk_get_bitlen(ctx) + 7) / 8;
445
0
}
Unexecuted instantiation: x509.c:mbedtls_pk_get_len
Unexecuted instantiation: x509_crl.c:mbedtls_pk_get_len
Unexecuted instantiation: x509_crt.c:mbedtls_pk_get_len
Unexecuted instantiation: x509write_csr.c:mbedtls_pk_get_len
Unexecuted instantiation: x509_create.c:mbedtls_pk_get_len
Unexecuted instantiation: x509write.c:mbedtls_pk_get_len
Unexecuted instantiation: oid.c:mbedtls_pk_get_len
Unexecuted instantiation: pk.c:mbedtls_pk_get_len
Unexecuted instantiation: pk_ecc.c:mbedtls_pk_get_len
Unexecuted instantiation: pk_wrap.c:mbedtls_pk_get_len
Unexecuted instantiation: pkparse.c:mbedtls_pk_get_len
Unexecuted instantiation: pkwrite.c:mbedtls_pk_get_len
Unexecuted instantiation: psa_crypto.c:mbedtls_pk_get_len
Unexecuted instantiation: psa_util.c:mbedtls_pk_get_len
Unexecuted instantiation: rsa.c:mbedtls_pk_get_len
Unexecuted instantiation: pkcs5.c:mbedtls_pk_get_len
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
 */
459
int 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
 */
489
int 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
 */
603
int 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
 */
650
int 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
 */
688
int 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
 */
721
int 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
 */
754
int 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
 */
778
int 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
 */
815
int 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
 */
852
int 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
 */
886
int 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
 */
923
int 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
 * \param ctx       The PK context to use. It must have been set up
934
 *                  with a private key.
935
 * \param input     Input to decrypt
936
 * \param ilen      Input size
937
 * \param output    Decrypted output
938
 * \param olen      Decrypted message length
939
 * \param osize     Size of the output buffer
940
 * \param f_rng     RNG function, must not be \c NULL.
941
 * \param p_rng     RNG parameter
942
 *
943
 * \note            For keys of type #MBEDTLS_PK_RSA, the signature algorithm is
944
 *                  either PKCS#1 v1.5 or OAEP, depending on the padding mode in
945
 *                  the underlying RSA context. For a pk object constructed by
946
 *                  parsing, this is PKCS#1 v1.5 by default.
947
 *
948
 * \return          0 on success, or a specific error code.
949
 */
950
int mbedtls_pk_decrypt(mbedtls_pk_context *ctx,
951
                       const unsigned char *input, size_t ilen,
952
                       unsigned char *output, size_t *olen, size_t osize,
953
                       mbedtls_f_rng_t *f_rng, void *p_rng);
954
955
/**
956
 * \brief           Encrypt message (including padding if relevant).
957
 *
958
 * \param ctx       The PK context to use. It must have been set up.
959
 * \param input     Message to encrypt
960
 * \param ilen      Message size
961
 * \param output    Encrypted output
962
 * \param olen      Encrypted output length
963
 * \param osize     Size of the output buffer
964
 * \param f_rng     RNG function, must not be \c NULL.
965
 * \param p_rng     RNG parameter
966
 *
967
 * \note            For keys of type #MBEDTLS_PK_RSA, the signature algorithm is
968
 *                  either PKCS#1 v1.5 or OAEP, depending on the padding mode in
969
 *                  the underlying RSA context. For a pk object constructed by
970
 *                  parsing, this is PKCS#1 v1.5 by default.
971
 *
972
 * \note            \p f_rng is used for padding generation.
973
 *
974
 * \return          0 on success, or a specific error code.
975
 */
976
int mbedtls_pk_encrypt(mbedtls_pk_context *ctx,
977
                       const unsigned char *input, size_t ilen,
978
                       unsigned char *output, size_t *olen, size_t osize,
979
                       mbedtls_f_rng_t *f_rng, void *p_rng);
980
981
/**
982
 * \brief           Check if a public-private pair of keys matches.
983
 *
984
 * \param pub       Context holding a public key.
985
 * \param prv       Context holding a private (and public) key.
986
 * \param f_rng     RNG function, must not be \c NULL.
987
 * \param p_rng     RNG parameter
988
 *
989
 * \return          \c 0 on success (keys were checked and match each other).
990
 * \return          #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the keys could not
991
 *                  be checked - in that case they may or may not match.
992
 * \return          #MBEDTLS_ERR_PK_BAD_INPUT_DATA if a context is invalid.
993
 * \return          Another non-zero value if the keys do not match.
994
 */
995
int mbedtls_pk_check_pair(const mbedtls_pk_context *pub,
996
                          const mbedtls_pk_context *prv,
997
                          mbedtls_f_rng_t *f_rng,
998
                          void *p_rng);
999
1000
/**
1001
 * \brief           Export debug information
1002
 *
1003
 * \param ctx       The PK context to use. It must have been initialized.
1004
 * \param items     Place to write debug items
1005
 *
1006
 * \return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
1007
 */
1008
int mbedtls_pk_debug(const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items);
1009
1010
/**
1011
 * \brief           Access the type name
1012
 *
1013
 * \param ctx       The PK context to use. It must have been initialized.
1014
 *
1015
 * \return          Type name on success, or "invalid PK"
1016
 */
1017
const char *mbedtls_pk_get_name(const mbedtls_pk_context *ctx);
1018
1019
/**
1020
 * \brief           Get the key type
1021
 *
1022
 * \param ctx       The PK context to use. It must have been initialized.
1023
 *
1024
 * \return          Type on success.
1025
 * \return          #MBEDTLS_PK_NONE for a context that has not been set up.
1026
 */
1027
mbedtls_pk_type_t mbedtls_pk_get_type(const mbedtls_pk_context *ctx);
1028
1029
#if defined(MBEDTLS_RSA_C)
1030
/**
1031
 * Quick access to an RSA context inside a PK context.
1032
 *
1033
 * \warning This function can only be used when the type of the context, as
1034
 * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_RSA.
1035
 * Ensuring that is the caller's responsibility.
1036
 * Alternatively, you can check whether this function returns NULL.
1037
 *
1038
 * \return The internal RSA context held by the PK context, or NULL.
1039
 */
1040
static inline mbedtls_rsa_context *mbedtls_pk_rsa(const mbedtls_pk_context pk)
1041
0
{
1042
0
    switch (mbedtls_pk_get_type(&pk)) {
1043
0
        case MBEDTLS_PK_RSA:
1044
0
            return (mbedtls_rsa_context *) (pk).MBEDTLS_PRIVATE(pk_ctx);
1045
0
        default:
1046
0
            return NULL;
1047
0
    }
1048
0
}
Unexecuted instantiation: x509.c:mbedtls_pk_rsa
Unexecuted instantiation: x509_crl.c:mbedtls_pk_rsa
Unexecuted instantiation: x509_crt.c:mbedtls_pk_rsa
Unexecuted instantiation: x509write_csr.c:mbedtls_pk_rsa
Unexecuted instantiation: x509_create.c:mbedtls_pk_rsa
Unexecuted instantiation: x509write.c:mbedtls_pk_rsa
Unexecuted instantiation: oid.c:mbedtls_pk_rsa
Unexecuted instantiation: pk.c:mbedtls_pk_rsa
Unexecuted instantiation: pk_ecc.c:mbedtls_pk_rsa
Unexecuted instantiation: pk_wrap.c:mbedtls_pk_rsa
Unexecuted instantiation: pkparse.c:mbedtls_pk_rsa
Unexecuted instantiation: pkwrite.c:mbedtls_pk_rsa
Unexecuted instantiation: psa_crypto.c:mbedtls_pk_rsa
Unexecuted instantiation: psa_util.c:mbedtls_pk_rsa
Unexecuted instantiation: rsa.c:mbedtls_pk_rsa
Unexecuted instantiation: pkcs5.c:mbedtls_pk_rsa
1049
#endif /* MBEDTLS_RSA_C */
1050
1051
#if defined(MBEDTLS_ECP_C)
1052
/**
1053
 * Quick access to an EC context inside a PK context.
1054
 *
1055
 * \warning This function can only be used when the type of the context, as
1056
 * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_ECKEY,
1057
 * #MBEDTLS_PK_ECKEY_DH, or #MBEDTLS_PK_ECDSA.
1058
 * Ensuring that is the caller's responsibility.
1059
 * Alternatively, you can check whether this function returns NULL.
1060
 *
1061
 * \return The internal EC context held by the PK context, or NULL.
1062
 */
1063
static inline mbedtls_ecp_keypair *mbedtls_pk_ec(const mbedtls_pk_context pk)
1064
0
{
1065
0
    switch (mbedtls_pk_get_type(&pk)) {
1066
0
        case MBEDTLS_PK_ECKEY:
1067
0
        case MBEDTLS_PK_ECKEY_DH:
1068
0
        case MBEDTLS_PK_ECDSA:
1069
0
            return (mbedtls_ecp_keypair *) (pk).MBEDTLS_PRIVATE(pk_ctx);
1070
0
        default:
1071
            return NULL;
1072
0
    }
1073
0
}
Unexecuted instantiation: x509.c:mbedtls_pk_ec
Unexecuted instantiation: x509_crl.c:mbedtls_pk_ec
Unexecuted instantiation: x509_crt.c:mbedtls_pk_ec
Unexecuted instantiation: x509write_csr.c:mbedtls_pk_ec
Unexecuted instantiation: x509_create.c:mbedtls_pk_ec
Unexecuted instantiation: x509write.c:mbedtls_pk_ec
Unexecuted instantiation: oid.c:mbedtls_pk_ec
Unexecuted instantiation: pk.c:mbedtls_pk_ec
Unexecuted instantiation: pk_ecc.c:mbedtls_pk_ec
Unexecuted instantiation: pk_wrap.c:mbedtls_pk_ec
Unexecuted instantiation: pkparse.c:mbedtls_pk_ec
Unexecuted instantiation: pkwrite.c:mbedtls_pk_ec
Unexecuted instantiation: psa_crypto.c:mbedtls_pk_ec
Unexecuted instantiation: psa_util.c:mbedtls_pk_ec
Unexecuted instantiation: rsa.c:mbedtls_pk_ec
Unexecuted instantiation: pkcs5.c:mbedtls_pk_ec
1074
#endif /* MBEDTLS_ECP_C */
1075
1076
#if defined(MBEDTLS_PK_PARSE_C)
1077
/** \ingroup pk_module */
1078
/**
1079
 * \brief           Parse a private key in PEM or DER format
1080
 *
1081
 * \note            If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
1082
 *                  subsystem must have been initialized by calling
1083
 *                  psa_crypto_init() before calling this function.
1084
 *
1085
 * \param ctx       The PK context to fill. It must have been initialized
1086
 *                  but not set up.
1087
 * \param key       Input buffer to parse.
1088
 *                  The buffer must contain the input exactly, with no
1089
 *                  extra trailing material. For PEM, the buffer must
1090
 *                  contain a null-terminated string.
1091
 * \param keylen    Size of \b key in bytes.
1092
 *                  For PEM data, this includes the terminating null byte,
1093
 *                  so \p keylen must be equal to `strlen(key) + 1`.
1094
 * \param pwd       Optional password for decryption.
1095
 *                  Pass \c NULL if expecting a non-encrypted key.
1096
 *                  Pass a string of \p pwdlen bytes if expecting an encrypted
1097
 *                  key; a non-encrypted key will also be accepted.
1098
 *                  The empty password is not supported.
1099
 * \param pwdlen    Size of the password in bytes.
1100
 *                  Ignored if \p pwd is \c NULL.
1101
 * \param f_rng     RNG function, must not be \c NULL. Used for blinding.
1102
 * \param p_rng     RNG parameter
1103
 *
1104
 * \note            On entry, ctx must be empty, either freshly initialised
1105
 *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
1106
 *                  specific key type, check the result with mbedtls_pk_can_do().
1107
 *
1108
 * \note            The key is also checked for correctness.
1109
 *
1110
 * \return          0 if successful, or a specific PK or PEM error code
1111
 */
1112
int mbedtls_pk_parse_key(mbedtls_pk_context *ctx,
1113
                         const unsigned char *key, size_t keylen,
1114
                         const unsigned char *pwd, size_t pwdlen,
1115
                         mbedtls_f_rng_t *f_rng, void *p_rng);
1116
1117
/** \ingroup pk_module */
1118
/**
1119
 * \brief           Parse a public key in PEM or DER format
1120
 *
1121
 * \note            If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
1122
 *                  subsystem must have been initialized by calling
1123
 *                  psa_crypto_init() before calling this function.
1124
 *
1125
 * \param ctx       The PK context to fill. It must have been initialized
1126
 *                  but not set up.
1127
 * \param key       Input buffer to parse.
1128
 *                  The buffer must contain the input exactly, with no
1129
 *                  extra trailing material. For PEM, the buffer must
1130
 *                  contain a null-terminated string.
1131
 * \param keylen    Size of \b key in bytes.
1132
 *                  For PEM data, this includes the terminating null byte,
1133
 *                  so \p keylen must be equal to `strlen(key) + 1`.
1134
 *
1135
 * \note            On entry, ctx must be empty, either freshly initialised
1136
 *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
1137
 *                  specific key type, check the result with mbedtls_pk_can_do().
1138
 *
1139
 * \note            For compressed points, see #MBEDTLS_ECP_PF_COMPRESSED for
1140
 *                  limitations.
1141
 *
1142
 * \note            The key is also checked for correctness.
1143
 *
1144
 * \return          0 if successful, or a specific PK or PEM error code
1145
 */
1146
int mbedtls_pk_parse_public_key(mbedtls_pk_context *ctx,
1147
                                const unsigned char *key, size_t keylen);
1148
1149
#if defined(MBEDTLS_FS_IO)
1150
/** \ingroup pk_module */
1151
/**
1152
 * \brief           Load and parse a private key
1153
 *
1154
 * \note            If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
1155
 *                  subsystem must have been initialized by calling
1156
 *                  psa_crypto_init() before calling this function.
1157
 *
1158
 * \param ctx       The PK context to fill. It must have been initialized
1159
 *                  but not set up.
1160
 * \param path      filename to read the private key from
1161
 * \param password  Optional password to decrypt the file.
1162
 *                  Pass \c NULL if expecting a non-encrypted key.
1163
 *                  Pass a null-terminated string if expecting an encrypted
1164
 *                  key; a non-encrypted key will also be accepted.
1165
 *                  The empty password is not supported.
1166
 * \param f_rng     RNG function, must not be \c NULL. Used for blinding.
1167
 * \param p_rng     RNG parameter
1168
 *
1169
 * \note            On entry, ctx must be empty, either freshly initialised
1170
 *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
1171
 *                  specific key type, check the result with mbedtls_pk_can_do().
1172
 *
1173
 * \note            The key is also checked for correctness.
1174
 *
1175
 * \return          0 if successful, or a specific PK or PEM error code
1176
 */
1177
int mbedtls_pk_parse_keyfile(mbedtls_pk_context *ctx,
1178
                             const char *path, const char *password,
1179
                             mbedtls_f_rng_t *f_rng, void *p_rng);
1180
1181
/** \ingroup pk_module */
1182
/**
1183
 * \brief           Load and parse a public key
1184
 *
1185
 * \param ctx       The PK context to fill. It must have been initialized
1186
 *                  but not set up.
1187
 * \param path      filename to read the public key from
1188
 *
1189
 * \note            On entry, ctx must be empty, either freshly initialised
1190
 *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If
1191
 *                  you need a specific key type, check the result with
1192
 *                  mbedtls_pk_can_do().
1193
 *
1194
 * \note            The key is also checked for correctness.
1195
 *
1196
 * \return          0 if successful, or a specific PK or PEM error code
1197
 */
1198
int mbedtls_pk_parse_public_keyfile(mbedtls_pk_context *ctx, const char *path);
1199
#endif /* MBEDTLS_FS_IO */
1200
#endif /* MBEDTLS_PK_PARSE_C */
1201
1202
#if defined(MBEDTLS_PK_WRITE_C)
1203
/**
1204
 * \brief           Write a private key to a PKCS#1 or SEC1 DER structure
1205
 *                  Note: data is written at the end of the buffer! Use the
1206
 *                        return value to determine where you should start
1207
 *                        using the buffer
1208
 *
1209
 * \param ctx       PK context which must contain a valid private key.
1210
 * \param buf       buffer to write to
1211
 * \param size      size of the buffer
1212
 *
1213
 * \return          length of data written if successful, or a specific
1214
 *                  error code
1215
 */
1216
int mbedtls_pk_write_key_der(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1217
1218
/**
1219
 * \brief           Write a public key to a SubjectPublicKeyInfo DER structure
1220
 *                  Note: data is written at the end of the buffer! Use the
1221
 *                        return value to determine where you should start
1222
 *                        using the buffer
1223
 *
1224
 * \param ctx       PK context which must contain a valid public or private key.
1225
 * \param buf       buffer to write to
1226
 * \param size      size of the buffer
1227
 *
1228
 * \return          length of data written if successful, or a specific
1229
 *                  error code
1230
 */
1231
int mbedtls_pk_write_pubkey_der(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1232
1233
#if defined(MBEDTLS_PEM_WRITE_C)
1234
/**
1235
 * \brief           Write a public key to a PEM string
1236
 *
1237
 * \param ctx       PK context which must contain a valid public or private key.
1238
 * \param buf       Buffer to write to. The output includes a
1239
 *                  terminating null byte.
1240
 * \param size      Size of the buffer in bytes.
1241
 *
1242
 * \return          0 if successful, or a specific error code
1243
 */
1244
int mbedtls_pk_write_pubkey_pem(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1245
1246
/**
1247
 * \brief           Write a private key to a PKCS#1 or SEC1 PEM string
1248
 *
1249
 * \param ctx       PK context which must contain a valid private key.
1250
 * \param buf       Buffer to write to. The output includes a
1251
 *                  terminating null byte.
1252
 * \param size      Size of the buffer in bytes.
1253
 *
1254
 * \return          0 if successful, or a specific error code
1255
 */
1256
int mbedtls_pk_write_key_pem(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
1257
#endif /* MBEDTLS_PEM_WRITE_C */
1258
#endif /* MBEDTLS_PK_WRITE_C */
1259
1260
/*
1261
 * WARNING: Low-level functions. You probably do not want to use these unless
1262
 *          you are certain you do ;)
1263
 */
1264
1265
#if defined(MBEDTLS_PK_PARSE_C)
1266
/**
1267
 * \brief           Parse a SubjectPublicKeyInfo DER structure
1268
 *
1269
 * \param p         the position in the ASN.1 data
1270
 * \param end       end of the buffer
1271
 * \param pk        The PK context to fill. It must have been initialized
1272
 *                  but not set up.
1273
 *
1274
 * \return          0 if successful, or a specific PK error code
1275
 */
1276
int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
1277
                               mbedtls_pk_context *pk);
1278
#endif /* MBEDTLS_PK_PARSE_C */
1279
1280
#if defined(MBEDTLS_PK_WRITE_C)
1281
/**
1282
 * \brief           Write a subjectPublicKey to ASN.1 data
1283
 *                  Note: function works backwards in data buffer
1284
 *
1285
 * \param p         reference to current position pointer
1286
 * \param start     start of the buffer (for bounds-checking)
1287
 * \param key       PK context which must contain a valid public or private key.
1288
 *
1289
 * \return          the length written or a negative error code
1290
 */
1291
int mbedtls_pk_write_pubkey(unsigned char **p, unsigned char *start,
1292
                            const mbedtls_pk_context *key);
1293
#endif /* MBEDTLS_PK_WRITE_C */
1294
1295
#ifdef __cplusplus
1296
}
1297
#endif
1298
1299
#endif /* MBEDTLS_PK_H */