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