xref: /reactos/sdk/include/reactos/libs/mbedtls/pk.h (revision cbda039f)
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  *  This file is provided under the Apache License 2.0, or the
11  *  GNU General Public License v2.0 or later.
12  *
13  *  **********
14  *  Apache License 2.0:
15  *
16  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
17  *  not use this file except in compliance with the License.
18  *  You may obtain a copy of the License at
19  *
20  *  http://www.apache.org/licenses/LICENSE-2.0
21  *
22  *  Unless required by applicable law or agreed to in writing, software
23  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
24  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25  *  See the License for the specific language governing permissions and
26  *  limitations under the License.
27  *
28  *  **********
29  *
30  *  **********
31  *  GNU General Public License v2.0 or later:
32  *
33  *  This program is free software; you can redistribute it and/or modify
34  *  it under the terms of the GNU General Public License as published by
35  *  the Free Software Foundation; either version 2 of the License, or
36  *  (at your option) any later version.
37  *
38  *  This program is distributed in the hope that it will be useful,
39  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
40  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41  *  GNU General Public License for more details.
42  *
43  *  You should have received a copy of the GNU General Public License along
44  *  with this program; if not, write to the Free Software Foundation, Inc.,
45  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
46  *
47  *  **********
48  */
49 
50 #ifndef MBEDTLS_PK_H
51 #define MBEDTLS_PK_H
52 
53 #if !defined(MBEDTLS_CONFIG_FILE)
54 #include "config.h"
55 #else
56 #include MBEDTLS_CONFIG_FILE
57 #endif
58 
59 #include "md.h"
60 
61 #if defined(MBEDTLS_RSA_C)
62 #include "rsa.h"
63 #endif
64 
65 #if defined(MBEDTLS_ECP_C)
66 #include "ecp.h"
67 #endif
68 
69 #if defined(MBEDTLS_ECDSA_C)
70 #include "ecdsa.h"
71 #endif
72 
73 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
74     !defined(inline) && !defined(__cplusplus)
75 #define inline __inline
76 #endif
77 
78 #define MBEDTLS_ERR_PK_ALLOC_FAILED        -0x3F80  /**< Memory allocation failed. */
79 #define MBEDTLS_ERR_PK_TYPE_MISMATCH       -0x3F00  /**< Type mismatch, eg attempt to encrypt with an ECDSA key */
80 #define MBEDTLS_ERR_PK_BAD_INPUT_DATA      -0x3E80  /**< Bad input parameters to function. */
81 #define MBEDTLS_ERR_PK_FILE_IO_ERROR       -0x3E00  /**< Read/write of file failed. */
82 #define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80  /**< Unsupported key version */
83 #define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT  -0x3D00  /**< Invalid key tag or value. */
84 #define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG      -0x3C80  /**< Key algorithm is unsupported (only RSA and EC are supported). */
85 #define MBEDTLS_ERR_PK_PASSWORD_REQUIRED   -0x3C00  /**< Private key password can't be empty. */
86 #define MBEDTLS_ERR_PK_PASSWORD_MISMATCH   -0x3B80  /**< Given private key password does not allow for correct decryption. */
87 #define MBEDTLS_ERR_PK_INVALID_PUBKEY      -0x3B00  /**< The pubkey tag or value is invalid (only RSA and EC are supported). */
88 #define MBEDTLS_ERR_PK_INVALID_ALG         -0x3A80  /**< The algorithm tag or value is invalid. */
89 #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00  /**< Elliptic curve is unsupported (only NIST curves are supported). */
90 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980  /**< Unavailable feature, e.g. RSA disabled for RSA key. */
91 #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900  /**< The buffer contains a valid signature followed by more data. */
92 
93 /* MBEDTLS_ERR_PK_HW_ACCEL_FAILED is deprecated and should not be used. */
94 #define MBEDTLS_ERR_PK_HW_ACCEL_FAILED     -0x3880  /**< PK hardware accelerator failed. */
95 
96 #ifdef __cplusplus
97 extern "C" {
98 #endif
99 
100 /**
101  * \brief          Public key types
102  */
103 typedef enum {
104     MBEDTLS_PK_NONE=0,
105     MBEDTLS_PK_RSA,
106     MBEDTLS_PK_ECKEY,
107     MBEDTLS_PK_ECKEY_DH,
108     MBEDTLS_PK_ECDSA,
109     MBEDTLS_PK_RSA_ALT,
110     MBEDTLS_PK_RSASSA_PSS,
111 } mbedtls_pk_type_t;
112 
113 /**
114  * \brief           Options for RSASSA-PSS signature verification.
115  *                  See \c mbedtls_rsa_rsassa_pss_verify_ext()
116  */
117 typedef struct mbedtls_pk_rsassa_pss_options
118 {
119     mbedtls_md_type_t mgf1_hash_id;
120     int expected_salt_len;
121 
122 } mbedtls_pk_rsassa_pss_options;
123 
124 /**
125  * \brief           Types for interfacing with the debug module
126  */
127 typedef enum
128 {
129     MBEDTLS_PK_DEBUG_NONE = 0,
130     MBEDTLS_PK_DEBUG_MPI,
131     MBEDTLS_PK_DEBUG_ECP,
132 } mbedtls_pk_debug_type;
133 
134 /**
135  * \brief           Item to send to the debug module
136  */
137 typedef struct mbedtls_pk_debug_item
138 {
139     mbedtls_pk_debug_type type;
140     const char *name;
141     void *value;
142 } mbedtls_pk_debug_item;
143 
144 /** Maximum number of item send for debugging, plus 1 */
145 #define MBEDTLS_PK_DEBUG_MAX_ITEMS 3
146 
147 /**
148  * \brief           Public key information and operations
149  */
150 typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
151 
152 /**
153  * \brief           Public key container
154  */
155 typedef struct mbedtls_pk_context
156 {
157     const mbedtls_pk_info_t *   pk_info; /**< Public key information         */
158     void *                      pk_ctx;  /**< Underlying public key context  */
159 } mbedtls_pk_context;
160 
161 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
162 /**
163  * \brief           Context for resuming operations
164  */
165 typedef struct
166 {
167     const mbedtls_pk_info_t *   pk_info; /**< Public key information         */
168     void *                      rs_ctx;  /**< Underlying restart context     */
169 } mbedtls_pk_restart_ctx;
170 #else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
171 /* Now we can declare functions that take a pointer to that */
172 typedef void mbedtls_pk_restart_ctx;
173 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
174 
175 #if defined(MBEDTLS_RSA_C)
176 /**
177  * Quick access to an RSA context inside a PK context.
178  *
179  * \warning You must make sure the PK context actually holds an RSA context
180  * before using this function!
181  */
mbedtls_pk_rsa(const mbedtls_pk_context pk)182 static inline mbedtls_rsa_context *mbedtls_pk_rsa( const mbedtls_pk_context pk )
183 {
184     return( (mbedtls_rsa_context *) (pk).pk_ctx );
185 }
186 #endif /* MBEDTLS_RSA_C */
187 
188 #if defined(MBEDTLS_ECP_C)
189 /**
190  * Quick access to an EC context inside a PK context.
191  *
192  * \warning You must make sure the PK context actually holds an EC context
193  * before using this function!
194  */
mbedtls_pk_ec(const mbedtls_pk_context pk)195 static inline mbedtls_ecp_keypair *mbedtls_pk_ec( const mbedtls_pk_context pk )
196 {
197     return( (mbedtls_ecp_keypair *) (pk).pk_ctx );
198 }
199 #endif /* MBEDTLS_ECP_C */
200 
201 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
202 /**
203  * \brief           Types for RSA-alt abstraction
204  */
205 typedef int (*mbedtls_pk_rsa_alt_decrypt_func)( void *ctx, int mode, size_t *olen,
206                     const unsigned char *input, unsigned char *output,
207                     size_t output_max_len );
208 typedef int (*mbedtls_pk_rsa_alt_sign_func)( void *ctx,
209                     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
210                     int mode, mbedtls_md_type_t md_alg, unsigned int hashlen,
211                     const unsigned char *hash, unsigned char *sig );
212 typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)( void *ctx );
213 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
214 
215 /**
216  * \brief           Return information associated with the given PK type
217  *
218  * \param pk_type   PK type to search for.
219  *
220  * \return          The PK info associated with the type or NULL if not found.
221  */
222 const mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type );
223 
224 /**
225  * \brief           Initialize a #mbedtls_pk_context (as NONE).
226  *
227  * \param ctx       The context to initialize.
228  *                  This must not be \c NULL.
229  */
230 void mbedtls_pk_init( mbedtls_pk_context *ctx );
231 
232 /**
233  * \brief           Free the components of a #mbedtls_pk_context.
234  *
235  * \param ctx       The context to clear. It must have been initialized.
236  *                  If this is \c NULL, this function does nothing.
237  */
238 void mbedtls_pk_free( mbedtls_pk_context *ctx );
239 
240 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
241 /**
242  * \brief           Initialize a restart context
243  *
244  * \param ctx       The context to initialize.
245  *                  This must not be \c NULL.
246  */
247 void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx );
248 
249 /**
250  * \brief           Free the components of a restart context
251  *
252  * \param ctx       The context to clear. It must have been initialized.
253  *                  If this is \c NULL, this function does nothing.
254  */
255 void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx );
256 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
257 
258 /**
259  * \brief           Initialize a PK context with the information given
260  *                  and allocates the type-specific PK subcontext.
261  *
262  * \param ctx       Context to initialize. It must not have been set
263  *                  up yet (type #MBEDTLS_PK_NONE).
264  * \param info      Information to use
265  *
266  * \return          0 on success,
267  *                  MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input,
268  *                  MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
269  *
270  * \note            For contexts holding an RSA-alt key, use
271  *                  \c mbedtls_pk_setup_rsa_alt() instead.
272  */
273 int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info );
274 
275 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
276 /**
277  * \brief           Initialize an RSA-alt context
278  *
279  * \param ctx       Context to initialize. It must not have been set
280  *                  up yet (type #MBEDTLS_PK_NONE).
281  * \param key       RSA key pointer
282  * \param decrypt_func  Decryption function
283  * \param sign_func     Signing function
284  * \param key_len_func  Function returning key length in bytes
285  *
286  * \return          0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the
287  *                  context wasn't already initialized as RSA_ALT.
288  *
289  * \note            This function replaces \c mbedtls_pk_setup() for RSA-alt.
290  */
291 int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,
292                          mbedtls_pk_rsa_alt_decrypt_func decrypt_func,
293                          mbedtls_pk_rsa_alt_sign_func sign_func,
294                          mbedtls_pk_rsa_alt_key_len_func key_len_func );
295 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
296 
297 /**
298  * \brief           Get the size in bits of the underlying key
299  *
300  * \param ctx       The context to query. It must have been initialized.
301  *
302  * \return          Key size in bits, or 0 on error
303  */
304 size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx );
305 
306 /**
307  * \brief           Get the length in bytes of the underlying key
308  *
309  * \param ctx       The context to query. It must have been initialized.
310  *
311  * \return          Key length in bytes, or 0 on error
312  */
mbedtls_pk_get_len(const mbedtls_pk_context * ctx)313 static inline size_t mbedtls_pk_get_len( const mbedtls_pk_context *ctx )
314 {
315     return( ( mbedtls_pk_get_bitlen( ctx ) + 7 ) / 8 );
316 }
317 
318 /**
319  * \brief           Tell if a context can do the operation given by type
320  *
321  * \param ctx       The context to query. It must have been initialized.
322  * \param type      The desired type.
323  *
324  * \return          1 if the context can do operations on the given type.
325  * \return          0 if the context cannot do the operations on the given
326  *                  type. This is always the case for a context that has
327  *                  been initialized but not set up, or that has been
328  *                  cleared with mbedtls_pk_free().
329  */
330 int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type );
331 
332 /**
333  * \brief           Verify signature (including padding if relevant).
334  *
335  * \param ctx       The PK context to use. It must have been set up.
336  * \param md_alg    Hash algorithm used (see notes)
337  * \param hash      Hash of the message to sign
338  * \param hash_len  Hash length or 0 (see notes)
339  * \param sig       Signature to verify
340  * \param sig_len   Signature length
341  *
342  * \return          0 on success (signature is valid),
343  *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
344  *                  signature in sig but its length is less than \p siglen,
345  *                  or a specific error code.
346  *
347  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
348  *                  Use \c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... )
349  *                  to verify RSASSA_PSS signatures.
350  *
351  * \note            If hash_len is 0, then the length associated with md_alg
352  *                  is used instead, or an error returned if it is invalid.
353  *
354  * \note            md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0
355  */
356 int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
357                const unsigned char *hash, size_t hash_len,
358                const unsigned char *sig, size_t sig_len );
359 
360 /**
361  * \brief           Restartable version of \c mbedtls_pk_verify()
362  *
363  * \note            Performs the same job as \c mbedtls_pk_verify(), but can
364  *                  return early and restart according to the limit set with
365  *                  \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
366  *                  operations. For RSA, same as \c mbedtls_pk_verify().
367  *
368  * \param ctx       The PK context to use. It must have been set up.
369  * \param md_alg    Hash algorithm used (see notes)
370  * \param hash      Hash of the message to sign
371  * \param hash_len  Hash length or 0 (see notes)
372  * \param sig       Signature to verify
373  * \param sig_len   Signature length
374  * \param rs_ctx    Restart context (NULL to disable restart)
375  *
376  * \return          See \c mbedtls_pk_verify(), or
377  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
378  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
379  */
380 int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx,
381                mbedtls_md_type_t md_alg,
382                const unsigned char *hash, size_t hash_len,
383                const unsigned char *sig, size_t sig_len,
384                mbedtls_pk_restart_ctx *rs_ctx );
385 
386 /**
387  * \brief           Verify signature, with options.
388  *                  (Includes verification of the padding depending on type.)
389  *
390  * \param type      Signature type (inc. possible padding type) to verify
391  * \param options   Pointer to type-specific options, or NULL
392  * \param ctx       The PK context to use. It must have been set up.
393  * \param md_alg    Hash algorithm used (see notes)
394  * \param hash      Hash of the message to sign
395  * \param hash_len  Hash length or 0 (see notes)
396  * \param sig       Signature to verify
397  * \param sig_len   Signature length
398  *
399  * \return          0 on success (signature is valid),
400  *                  #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
401  *                  used for this type of signatures,
402  *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
403  *                  signature in sig but its length is less than \p siglen,
404  *                  or a specific error code.
405  *
406  * \note            If hash_len is 0, then the length associated with md_alg
407  *                  is used instead, or an error returned if it is invalid.
408  *
409  * \note            md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0
410  *
411  * \note            If type is MBEDTLS_PK_RSASSA_PSS, then options must point
412  *                  to a mbedtls_pk_rsassa_pss_options structure,
413  *                  otherwise it must be NULL.
414  */
415 int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
416                    mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
417                    const unsigned char *hash, size_t hash_len,
418                    const unsigned char *sig, size_t sig_len );
419 
420 /**
421  * \brief           Make signature, including padding if relevant.
422  *
423  * \param ctx       The PK context to use. It must have been set up
424  *                  with a private key.
425  * \param md_alg    Hash algorithm used (see notes)
426  * \param hash      Hash of the message to sign
427  * \param hash_len  Hash length or 0 (see notes)
428  * \param sig       Place to write the signature
429  * \param sig_len   Number of bytes written
430  * \param f_rng     RNG function
431  * \param p_rng     RNG parameter
432  *
433  * \return          0 on success, or a specific error code.
434  *
435  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
436  *                  There is no interface in the PK module to make RSASSA-PSS
437  *                  signatures yet.
438  *
439  * \note            If hash_len is 0, then the length associated with md_alg
440  *                  is used instead, or an error returned if it is invalid.
441  *
442  * \note            For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0.
443  *                  For ECDSA, md_alg may never be MBEDTLS_MD_NONE.
444  *
445  * \note            In order to ensure enough space for the signature, the
446  *                  \p sig buffer size must be of at least
447  *                  `max(MBEDTLS_ECDSA_MAX_LEN, MBEDTLS_MPI_MAX_SIZE)` bytes.
448  */
449 int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
450              const unsigned char *hash, size_t hash_len,
451              unsigned char *sig, size_t *sig_len,
452              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
453 
454 /**
455  * \brief           Restartable version of \c mbedtls_pk_sign()
456  *
457  * \note            Performs the same job as \c mbedtls_pk_sign(), but can
458  *                  return early and restart according to the limit set with
459  *                  \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
460  *                  operations. For RSA, same as \c mbedtls_pk_sign().
461  *
462  * \note            In order to ensure enough space for the signature, the
463  *                  \p sig buffer size must be of at least
464  *                  `max(MBEDTLS_ECDSA_MAX_LEN, MBEDTLS_MPI_MAX_SIZE)` bytes.
465  *
466  * \param ctx       The PK context to use. It must have been set up
467  *                  with a private key.
468  * \param md_alg    Hash algorithm used (see notes)
469  * \param hash      Hash of the message to sign
470  * \param hash_len  Hash length or 0 (see notes)
471  * \param sig       Place to write the signature
472  * \param sig_len   Number of bytes written
473  * \param f_rng     RNG function
474  * \param p_rng     RNG parameter
475  * \param rs_ctx    Restart context (NULL to disable restart)
476  *
477  * \return          See \c mbedtls_pk_sign(), or
478  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
479  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
480  */
481 int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx,
482              mbedtls_md_type_t md_alg,
483              const unsigned char *hash, size_t hash_len,
484              unsigned char *sig, size_t *sig_len,
485              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
486              mbedtls_pk_restart_ctx *rs_ctx );
487 
488 /**
489  * \brief           Decrypt message (including padding if relevant).
490  *
491  * \param ctx       The PK context to use. It must have been set up
492  *                  with a private key.
493  * \param input     Input to decrypt
494  * \param ilen      Input size
495  * \param output    Decrypted output
496  * \param olen      Decrypted message length
497  * \param osize     Size of the output buffer
498  * \param f_rng     RNG function
499  * \param p_rng     RNG parameter
500  *
501  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
502  *
503  * \return          0 on success, or a specific error code.
504  */
505 int mbedtls_pk_decrypt( mbedtls_pk_context *ctx,
506                 const unsigned char *input, size_t ilen,
507                 unsigned char *output, size_t *olen, size_t osize,
508                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
509 
510 /**
511  * \brief           Encrypt message (including padding if relevant).
512  *
513  * \param ctx       The PK context to use. It must have been set up.
514  * \param input     Message to encrypt
515  * \param ilen      Message size
516  * \param output    Encrypted output
517  * \param olen      Encrypted output length
518  * \param osize     Size of the output buffer
519  * \param f_rng     RNG function
520  * \param p_rng     RNG parameter
521  *
522  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
523  *
524  * \return          0 on success, or a specific error code.
525  */
526 int mbedtls_pk_encrypt( mbedtls_pk_context *ctx,
527                 const unsigned char *input, size_t ilen,
528                 unsigned char *output, size_t *olen, size_t osize,
529                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
530 
531 /**
532  * \brief           Check if a public-private pair of keys matches.
533  *
534  * \param pub       Context holding a public key.
535  * \param prv       Context holding a private (and public) key.
536  *
537  * \return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
538  */
539 int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv );
540 
541 /**
542  * \brief           Export debug information
543  *
544  * \param ctx       The PK context to use. It must have been initialized.
545  * \param items     Place to write debug items
546  *
547  * \return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
548  */
549 int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items );
550 
551 /**
552  * \brief           Access the type name
553  *
554  * \param ctx       The PK context to use. It must have been initialized.
555  *
556  * \return          Type name on success, or "invalid PK"
557  */
558 const char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx );
559 
560 /**
561  * \brief           Get the key type
562  *
563  * \param ctx       The PK context to use. It must have been initialized.
564  *
565  * \return          Type on success.
566  * \return          #MBEDTLS_PK_NONE for a context that has not been set up.
567  */
568 mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );
569 
570 #if defined(MBEDTLS_PK_PARSE_C)
571 /** \ingroup pk_module */
572 /**
573  * \brief           Parse a private key in PEM or DER format
574  *
575  * \param ctx       The PK context to fill. It must have been initialized
576  *                  but not set up.
577  * \param key       Input buffer to parse.
578  *                  The buffer must contain the input exactly, with no
579  *                  extra trailing material. For PEM, the buffer must
580  *                  contain a null-terminated string.
581  * \param keylen    Size of \b key in bytes.
582  *                  For PEM data, this includes the terminating null byte,
583  *                  so \p keylen must be equal to `strlen(key) + 1`.
584  * \param pwd       Optional password for decryption.
585  *                  Pass \c NULL if expecting a non-encrypted key.
586  *                  Pass a string of \p pwdlen bytes if expecting an encrypted
587  *                  key; a non-encrypted key will also be accepted.
588  *                  The empty password is not supported.
589  * \param pwdlen    Size of the password in bytes.
590  *                  Ignored if \p pwd is \c NULL.
591  *
592  * \note            On entry, ctx must be empty, either freshly initialised
593  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
594  *                  specific key type, check the result with mbedtls_pk_can_do().
595  *
596  * \note            The key is also checked for correctness.
597  *
598  * \return          0 if successful, or a specific PK or PEM error code
599  */
600 int mbedtls_pk_parse_key( mbedtls_pk_context *ctx,
601                   const unsigned char *key, size_t keylen,
602                   const unsigned char *pwd, size_t pwdlen );
603 
604 /** \ingroup pk_module */
605 /**
606  * \brief           Parse a public key in PEM or DER format
607  *
608  * \param ctx       The PK context to fill. It must have been initialized
609  *                  but not set up.
610  * \param key       Input buffer to parse.
611  *                  The buffer must contain the input exactly, with no
612  *                  extra trailing material. For PEM, the buffer must
613  *                  contain a null-terminated string.
614  * \param keylen    Size of \b key in bytes.
615  *                  For PEM data, this includes the terminating null byte,
616  *                  so \p keylen must be equal to `strlen(key) + 1`.
617  *
618  * \note            On entry, ctx must be empty, either freshly initialised
619  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
620  *                  specific key type, check the result with mbedtls_pk_can_do().
621  *
622  * \note            The key is also checked for correctness.
623  *
624  * \return          0 if successful, or a specific PK or PEM error code
625  */
626 int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,
627                          const unsigned char *key, size_t keylen );
628 
629 #if defined(MBEDTLS_FS_IO)
630 /** \ingroup pk_module */
631 /**
632  * \brief           Load and parse a private key
633  *
634  * \param ctx       The PK context to fill. It must have been initialized
635  *                  but not set up.
636  * \param path      filename to read the private key from
637  * \param password  Optional password to decrypt the file.
638  *                  Pass \c NULL if expecting a non-encrypted key.
639  *                  Pass a null-terminated string if expecting an encrypted
640  *                  key; a non-encrypted key will also be accepted.
641  *                  The empty password is not supported.
642  *
643  * \note            On entry, ctx must be empty, either freshly initialised
644  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
645  *                  specific key type, check the result with mbedtls_pk_can_do().
646  *
647  * \note            The key is also checked for correctness.
648  *
649  * \return          0 if successful, or a specific PK or PEM error code
650  */
651 int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
652                       const char *path, const char *password );
653 
654 /** \ingroup pk_module */
655 /**
656  * \brief           Load and parse a public key
657  *
658  * \param ctx       The PK context to fill. It must have been initialized
659  *                  but not set up.
660  * \param path      filename to read the public key from
661  *
662  * \note            On entry, ctx must be empty, either freshly initialised
663  *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If
664  *                  you need a specific key type, check the result with
665  *                  mbedtls_pk_can_do().
666  *
667  * \note            The key is also checked for correctness.
668  *
669  * \return          0 if successful, or a specific PK or PEM error code
670  */
671 int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path );
672 #endif /* MBEDTLS_FS_IO */
673 #endif /* MBEDTLS_PK_PARSE_C */
674 
675 #if defined(MBEDTLS_PK_WRITE_C)
676 /**
677  * \brief           Write a private key to a PKCS#1 or SEC1 DER structure
678  *                  Note: data is written at the end of the buffer! Use the
679  *                        return value to determine where you should start
680  *                        using the buffer
681  *
682  * \param ctx       PK context which must contain a valid private key.
683  * \param buf       buffer to write to
684  * \param size      size of the buffer
685  *
686  * \return          length of data written if successful, or a specific
687  *                  error code
688  */
689 int mbedtls_pk_write_key_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
690 
691 /**
692  * \brief           Write a public key to a SubjectPublicKeyInfo DER structure
693  *                  Note: data is written at the end of the buffer! Use the
694  *                        return value to determine where you should start
695  *                        using the buffer
696  *
697  * \param ctx       PK context which must contain a valid public or private key.
698  * \param buf       buffer to write to
699  * \param size      size of the buffer
700  *
701  * \return          length of data written if successful, or a specific
702  *                  error code
703  */
704 int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
705 
706 #if defined(MBEDTLS_PEM_WRITE_C)
707 /**
708  * \brief           Write a public key to a PEM string
709  *
710  * \param ctx       PK context which must contain a valid public or private key.
711  * \param buf       Buffer to write to. The output includes a
712  *                  terminating null byte.
713  * \param size      Size of the buffer in bytes.
714  *
715  * \return          0 if successful, or a specific error code
716  */
717 int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
718 
719 /**
720  * \brief           Write a private key to a PKCS#1 or SEC1 PEM string
721  *
722  * \param ctx       PK context which must contain a valid private key.
723  * \param buf       Buffer to write to. The output includes a
724  *                  terminating null byte.
725  * \param size      Size of the buffer in bytes.
726  *
727  * \return          0 if successful, or a specific error code
728  */
729 int mbedtls_pk_write_key_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
730 #endif /* MBEDTLS_PEM_WRITE_C */
731 #endif /* MBEDTLS_PK_WRITE_C */
732 
733 /*
734  * WARNING: Low-level functions. You probably do not want to use these unless
735  *          you are certain you do ;)
736  */
737 
738 #if defined(MBEDTLS_PK_PARSE_C)
739 /**
740  * \brief           Parse a SubjectPublicKeyInfo DER structure
741  *
742  * \param p         the position in the ASN.1 data
743  * \param end       end of the buffer
744  * \param pk        The PK context to fill. It must have been initialized
745  *                  but not set up.
746  *
747  * \return          0 if successful, or a specific PK error code
748  */
749 int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,
750                         mbedtls_pk_context *pk );
751 #endif /* MBEDTLS_PK_PARSE_C */
752 
753 #if defined(MBEDTLS_PK_WRITE_C)
754 /**
755  * \brief           Write a subjectPublicKey to ASN.1 data
756  *                  Note: function works backwards in data buffer
757  *
758  * \param p         reference to current position pointer
759  * \param start     start of the buffer (for bounds-checking)
760  * \param key       PK context which must contain a valid public or private key.
761  *
762  * \return          the length written or a negative error code
763  */
764 int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,
765                      const mbedtls_pk_context *key );
766 #endif /* MBEDTLS_PK_WRITE_C */
767 
768 /*
769  * Internal module functions. You probably do not want to use these unless you
770  * know you do.
771  */
772 #if defined(MBEDTLS_FS_IO)
773 int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n );
774 #endif
775 
776 #ifdef __cplusplus
777 }
778 #endif
779 
780 #endif /* MBEDTLS_PK_H */
781