1 /*
2  *  Public Key layer for writing key files and structures
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #include "common.h"
21 
22 #if defined(MBEDTLS_PK_WRITE_C)
23 
24 #include "mbedtls/pk.h"
25 #include "mbedtls/asn1write.h"
26 #include "mbedtls/oid.h"
27 #include "mbedtls/platform_util.h"
28 #include "mbedtls/error.h"
29 
30 #include <string.h>
31 
32 #if defined(MBEDTLS_RSA_C)
33 #include "mbedtls/rsa.h"
34 #endif
35 #if defined(MBEDTLS_ECP_C)
36 #include "mbedtls/bignum.h"
37 #include "mbedtls/ecp.h"
38 #include "mbedtls/platform_util.h"
39 #endif
40 #if defined(MBEDTLS_ECDSA_C)
41 #include "mbedtls/ecdsa.h"
42 #endif
43 #if defined(MBEDTLS_PEM_WRITE_C)
44 #include "mbedtls/pem.h"
45 #endif
46 
47 #if defined(MBEDTLS_USE_PSA_CRYPTO)
48 #include "psa/crypto.h"
49 #include "mbedtls/psa_util.h"
50 #endif
51 #if defined(MBEDTLS_PLATFORM_C)
52 #include "mbedtls/platform.h"
53 #else
54 #include <stdlib.h>
55 #define mbedtls_calloc    calloc
56 #define mbedtls_free       free
57 #endif
58 
59 /* Parameter validation macros based on platform_util.h */
60 #define PK_VALIDATE_RET( cond )    \
61     MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA )
62 #define PK_VALIDATE( cond )        \
63     MBEDTLS_INTERNAL_VALIDATE( cond )
64 
65 #if defined(MBEDTLS_RSA_C)
66 /*
67  *  RSAPublicKey ::= SEQUENCE {
68  *      modulus           INTEGER,  -- n
69  *      publicExponent    INTEGER   -- e
70  *  }
71  */
pk_write_rsa_pubkey(unsigned char ** p,unsigned char * start,mbedtls_rsa_context * rsa)72 static int pk_write_rsa_pubkey( unsigned char **p, unsigned char *start,
73                                 mbedtls_rsa_context *rsa )
74 {
75     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
76     size_t len = 0;
77     mbedtls_mpi T;
78 
79     mbedtls_mpi_init( &T );
80 
81     /* Export E */
82     if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &T ) ) != 0 ||
83          ( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )
84         goto end_of_export;
85     len += ret;
86 
87     /* Export N */
88     if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL, NULL, NULL, NULL ) ) != 0 ||
89          ( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )
90         goto end_of_export;
91     len += ret;
92 
93 end_of_export:
94 
95     mbedtls_mpi_free( &T );
96     if( ret < 0 )
97         return( ret );
98 
99     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
100     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED |
101                                                  MBEDTLS_ASN1_SEQUENCE ) );
102 
103     return( (int) len );
104 }
105 #endif /* MBEDTLS_RSA_C */
106 
107 #if defined(MBEDTLS_ECP_C)
108 /*
109  * EC public key is an EC point
110  */
pk_write_ec_pubkey(unsigned char ** p,unsigned char * start,mbedtls_ecp_keypair * ec)111 static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,
112                                mbedtls_ecp_keypair *ec )
113 {
114     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
115     size_t len = 0;
116     unsigned char buf[MBEDTLS_ECP_MAX_PT_LEN];
117 
118     if( ( ret = mbedtls_ecp_point_write_binary( &ec->grp, &ec->Q,
119                                         MBEDTLS_ECP_PF_UNCOMPRESSED,
120                                         &len, buf, sizeof( buf ) ) ) != 0 )
121     {
122         return( ret );
123     }
124 
125     if( *p < start || (size_t)( *p - start ) < len )
126         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
127 
128     *p -= len;
129     memcpy( *p, buf, len );
130 
131     return( (int) len );
132 }
133 
134 /*
135  * ECParameters ::= CHOICE {
136  *   namedCurve         OBJECT IDENTIFIER
137  * }
138  */
pk_write_ec_param(unsigned char ** p,unsigned char * start,mbedtls_ecp_keypair * ec)139 static int pk_write_ec_param( unsigned char **p, unsigned char *start,
140                               mbedtls_ecp_keypair *ec )
141 {
142     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
143     size_t len = 0;
144     const char *oid;
145     size_t oid_len;
146 
147     if( ( ret = mbedtls_oid_get_oid_by_ec_grp( ec->grp.id, &oid, &oid_len ) ) != 0 )
148         return( ret );
149 
150     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) );
151 
152     return( (int) len );
153 }
154 
155 /*
156  * privateKey  OCTET STRING -- always of length ceil(log2(n)/8)
157  */
pk_write_ec_private(unsigned char ** p,unsigned char * start,mbedtls_ecp_keypair * ec)158 static int pk_write_ec_private( unsigned char **p, unsigned char *start,
159                                 mbedtls_ecp_keypair *ec )
160 {
161     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
162     size_t byte_length = ( ec->grp.pbits + 7 ) / 8;
163     unsigned char tmp[MBEDTLS_ECP_MAX_BYTES];
164 
165     ret = mbedtls_ecp_write_key( ec, tmp, byte_length );
166     if( ret != 0 )
167         goto exit;
168     ret = mbedtls_asn1_write_octet_string( p, start, tmp, byte_length );
169 
170 exit:
171     mbedtls_platform_zeroize( tmp, byte_length );
172     return( ret );
173 }
174 #endif /* MBEDTLS_ECP_C */
175 
mbedtls_pk_write_pubkey(unsigned char ** p,unsigned char * start,const mbedtls_pk_context * key)176 int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,
177                              const mbedtls_pk_context *key )
178 {
179     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
180     size_t len = 0;
181 
182     PK_VALIDATE_RET( p != NULL );
183     PK_VALIDATE_RET( *p != NULL );
184     PK_VALIDATE_RET( start != NULL );
185     PK_VALIDATE_RET( key != NULL );
186 
187 #if defined(MBEDTLS_RSA_C)
188     if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )
189         MBEDTLS_ASN1_CHK_ADD( len, pk_write_rsa_pubkey( p, start, mbedtls_pk_rsa( *key ) ) );
190     else
191 #endif
192 #if defined(MBEDTLS_ECP_C)
193     if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )
194         MBEDTLS_ASN1_CHK_ADD( len, pk_write_ec_pubkey( p, start, mbedtls_pk_ec( *key ) ) );
195     else
196 #endif
197 #if defined(MBEDTLS_USE_PSA_CRYPTO)
198     if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_OPAQUE )
199     {
200         size_t buffer_size;
201         psa_key_id_t* key_id = (psa_key_id_t*) key->pk_ctx;
202 
203         if ( *p < start )
204             return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
205 
206         buffer_size = (size_t)( *p - start );
207         if ( psa_export_public_key( *key_id, start, buffer_size, &len )
208              != PSA_SUCCESS )
209         {
210             return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
211         }
212         else
213         {
214             *p -= len;
215             memmove( *p, start, len );
216         }
217     }
218     else
219 #endif /* MBEDTLS_USE_PSA_CRYPTO */
220         return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
221 
222     return( (int) len );
223 }
224 
mbedtls_pk_write_pubkey_der(const mbedtls_pk_context * key,unsigned char * buf,size_t size)225 int mbedtls_pk_write_pubkey_der( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
226 {
227     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
228     unsigned char *c;
229     size_t len = 0, par_len = 0, oid_len;
230     mbedtls_pk_type_t pk_type;
231     const char *oid;
232 
233     PK_VALIDATE_RET( key != NULL );
234     if( size == 0 )
235         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
236     PK_VALIDATE_RET( buf != NULL );
237 
238     c = buf + size;
239 
240     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, key ) );
241 
242     if( c - buf < 1 )
243         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
244 
245     /*
246      *  SubjectPublicKeyInfo  ::=  SEQUENCE  {
247      *       algorithm            AlgorithmIdentifier,
248      *       subjectPublicKey     BIT STRING }
249      */
250     *--c = 0;
251     len += 1;
252 
253     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
254     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_BIT_STRING ) );
255 
256     pk_type = mbedtls_pk_get_type( key );
257 #if defined(MBEDTLS_ECP_C)
258     if( pk_type == MBEDTLS_PK_ECKEY )
259     {
260         MBEDTLS_ASN1_CHK_ADD( par_len, pk_write_ec_param( &c, buf, mbedtls_pk_ec( *key ) ) );
261     }
262 #endif
263 #if defined(MBEDTLS_USE_PSA_CRYPTO)
264     if( pk_type == MBEDTLS_PK_OPAQUE )
265     {
266         psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
267         psa_key_type_t key_type;
268         psa_key_id_t key_id;
269         psa_ecc_family_t curve;
270         size_t bits;
271 
272         key_id = *((psa_key_id_t*) key->pk_ctx );
273         if( PSA_SUCCESS != psa_get_key_attributes( key_id, &attributes ) )
274             return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
275         key_type = psa_get_key_type( &attributes );
276         bits = psa_get_key_bits( &attributes );
277         psa_reset_key_attributes( &attributes );
278 
279         curve = PSA_KEY_TYPE_ECC_GET_FAMILY( key_type );
280         if( curve == 0 )
281             return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
282 
283         ret = mbedtls_psa_get_ecc_oid_from_id( curve, bits, &oid, &oid_len );
284         if( ret != 0 )
285             return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
286 
287         /* Write EC algorithm parameters; that's akin
288          * to pk_write_ec_param() above. */
289         MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_oid( &c, buf,
290                                                                oid, oid_len ) );
291 
292         /* The rest of the function works as for legacy EC contexts. */
293         pk_type = MBEDTLS_PK_ECKEY;
294     }
295 #endif /* MBEDTLS_USE_PSA_CRYPTO */
296 
297     if( ( ret = mbedtls_oid_get_oid_by_pk_alg( pk_type, &oid,
298                                                &oid_len ) ) != 0 )
299     {
300         return( ret );
301     }
302 
303     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( &c, buf, oid, oid_len,
304                                                         par_len ) );
305 
306     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
307     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |
308                                                 MBEDTLS_ASN1_SEQUENCE ) );
309 
310     return( (int) len );
311 }
312 
mbedtls_pk_write_key_der(const mbedtls_pk_context * key,unsigned char * buf,size_t size)313 int mbedtls_pk_write_key_der( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
314 {
315     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
316     unsigned char *c;
317     size_t len = 0;
318 
319     PK_VALIDATE_RET( key != NULL );
320     if( size == 0 )
321         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
322     PK_VALIDATE_RET( buf != NULL );
323 
324     c = buf + size;
325 
326 #if defined(MBEDTLS_RSA_C)
327     if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )
328     {
329         mbedtls_mpi T; /* Temporary holding the exported parameters */
330         mbedtls_rsa_context *rsa = mbedtls_pk_rsa( *key );
331 
332         /*
333          * Export the parameters one after another to avoid simultaneous copies.
334          */
335 
336         mbedtls_mpi_init( &T );
337 
338         /* Export QP */
339         if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, NULL, &T ) ) != 0 ||
340             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
341             goto end_of_export;
342         len += ret;
343 
344         /* Export DQ */
345         if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, &T, NULL ) ) != 0 ||
346             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
347             goto end_of_export;
348         len += ret;
349 
350         /* Export DP */
351         if( ( ret = mbedtls_rsa_export_crt( rsa, &T, NULL, NULL ) ) != 0 ||
352             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
353             goto end_of_export;
354         len += ret;
355 
356         /* Export Q */
357         if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
358                                          &T, NULL, NULL ) ) != 0 ||
359              ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
360             goto end_of_export;
361         len += ret;
362 
363         /* Export P */
364         if ( ( ret = mbedtls_rsa_export( rsa, NULL, &T,
365                                          NULL, NULL, NULL ) ) != 0 ||
366              ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
367             goto end_of_export;
368         len += ret;
369 
370         /* Export D */
371         if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
372                                          NULL, &T, NULL ) ) != 0 ||
373              ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
374             goto end_of_export;
375         len += ret;
376 
377         /* Export E */
378         if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
379                                          NULL, NULL, &T ) ) != 0 ||
380              ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
381             goto end_of_export;
382         len += ret;
383 
384         /* Export N */
385         if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL,
386                                          NULL, NULL, NULL ) ) != 0 ||
387              ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
388             goto end_of_export;
389         len += ret;
390 
391     end_of_export:
392 
393         mbedtls_mpi_free( &T );
394         if( ret < 0 )
395             return( ret );
396 
397         MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) );
398         MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
399         MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c,
400                                                buf, MBEDTLS_ASN1_CONSTRUCTED |
401                                                MBEDTLS_ASN1_SEQUENCE ) );
402     }
403     else
404 #endif /* MBEDTLS_RSA_C */
405 #if defined(MBEDTLS_ECP_C)
406     if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )
407     {
408         mbedtls_ecp_keypair *ec = mbedtls_pk_ec( *key );
409         size_t pub_len = 0, par_len = 0;
410 
411         /*
412          * RFC 5915, or SEC1 Appendix C.4
413          *
414          * ECPrivateKey ::= SEQUENCE {
415          *      version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
416          *      privateKey     OCTET STRING,
417          *      parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
418          *      publicKey  [1] BIT STRING OPTIONAL
419          *    }
420          */
421 
422         /* publicKey */
423         MBEDTLS_ASN1_CHK_ADD( pub_len, pk_write_ec_pubkey( &c, buf, ec ) );
424 
425         if( c - buf < 1 )
426             return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
427         *--c = 0;
428         pub_len += 1;
429 
430         MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_len( &c, buf, pub_len ) );
431         MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_BIT_STRING ) );
432 
433         MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_len( &c, buf, pub_len ) );
434         MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_tag( &c, buf,
435                             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) );
436         len += pub_len;
437 
438         /* parameters */
439         MBEDTLS_ASN1_CHK_ADD( par_len, pk_write_ec_param( &c, buf, ec ) );
440 
441         MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_len( &c, buf, par_len ) );
442         MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_tag( &c, buf,
443                             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) );
444         len += par_len;
445 
446         /* privateKey */
447         MBEDTLS_ASN1_CHK_ADD( len, pk_write_ec_private( &c, buf, ec ) );
448 
449         /* version */
450         MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 1 ) );
451 
452         MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
453         MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |
454                                                     MBEDTLS_ASN1_SEQUENCE ) );
455     }
456     else
457 #endif /* MBEDTLS_ECP_C */
458         return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
459 
460     return( (int) len );
461 }
462 
463 #if defined(MBEDTLS_PEM_WRITE_C)
464 
465 #define PEM_BEGIN_PUBLIC_KEY    "-----BEGIN PUBLIC KEY-----\n"
466 #define PEM_END_PUBLIC_KEY      "-----END PUBLIC KEY-----\n"
467 
468 #define PEM_BEGIN_PRIVATE_KEY_RSA   "-----BEGIN RSA PRIVATE KEY-----\n"
469 #define PEM_END_PRIVATE_KEY_RSA     "-----END RSA PRIVATE KEY-----\n"
470 #define PEM_BEGIN_PRIVATE_KEY_EC    "-----BEGIN EC PRIVATE KEY-----\n"
471 #define PEM_END_PRIVATE_KEY_EC      "-----END EC PRIVATE KEY-----\n"
472 
473 /*
474  * Max sizes of key per types. Shown as tag + len (+ content).
475  */
476 
477 #if defined(MBEDTLS_RSA_C)
478 /*
479  * RSA public keys:
480  *  SubjectPublicKeyInfo  ::=  SEQUENCE  {          1 + 3
481  *       algorithm            AlgorithmIdentifier,  1 + 1 (sequence)
482  *                                                + 1 + 1 + 9 (rsa oid)
483  *                                                + 1 + 1 (params null)
484  *       subjectPublicKey     BIT STRING }          1 + 3 + (1 + below)
485  *  RSAPublicKey ::= SEQUENCE {                     1 + 3
486  *      modulus           INTEGER,  -- n            1 + 3 + MPI_MAX + 1
487  *      publicExponent    INTEGER   -- e            1 + 3 + MPI_MAX + 1
488  *  }
489  */
490 #define RSA_PUB_DER_MAX_BYTES   ( 38 + 2 * MBEDTLS_MPI_MAX_SIZE )
491 
492 /*
493  * RSA private keys:
494  *  RSAPrivateKey ::= SEQUENCE {                    1 + 3
495  *      version           Version,                  1 + 1 + 1
496  *      modulus           INTEGER,                  1 + 3 + MPI_MAX + 1
497  *      publicExponent    INTEGER,                  1 + 3 + MPI_MAX + 1
498  *      privateExponent   INTEGER,                  1 + 3 + MPI_MAX + 1
499  *      prime1            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
500  *      prime2            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
501  *      exponent1         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
502  *      exponent2         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
503  *      coefficient       INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
504  *      otherPrimeInfos   OtherPrimeInfos OPTIONAL  0 (not supported)
505  *  }
506  */
507 #define MPI_MAX_SIZE_2          ( MBEDTLS_MPI_MAX_SIZE / 2 + \
508                                   MBEDTLS_MPI_MAX_SIZE % 2 )
509 #define RSA_PRV_DER_MAX_BYTES   ( 47 + 3 * MBEDTLS_MPI_MAX_SIZE \
510                                    + 5 * MPI_MAX_SIZE_2 )
511 
512 #else /* MBEDTLS_RSA_C */
513 
514 #define RSA_PUB_DER_MAX_BYTES   0
515 #define RSA_PRV_DER_MAX_BYTES   0
516 
517 #endif /* MBEDTLS_RSA_C */
518 
519 #if defined(MBEDTLS_ECP_C)
520 /*
521  * EC public keys:
522  *  SubjectPublicKeyInfo  ::=  SEQUENCE  {      1 + 2
523  *    algorithm         AlgorithmIdentifier,    1 + 1 (sequence)
524  *                                            + 1 + 1 + 7 (ec oid)
525  *                                            + 1 + 1 + 9 (namedCurve oid)
526  *    subjectPublicKey  BIT STRING              1 + 2 + 1               [1]
527  *                                            + 1 (point format)        [1]
528  *                                            + 2 * ECP_MAX (coords)    [1]
529  *  }
530  */
531 #define ECP_PUB_DER_MAX_BYTES   ( 30 + 2 * MBEDTLS_ECP_MAX_BYTES )
532 
533 /*
534  * EC private keys:
535  * ECPrivateKey ::= SEQUENCE {                  1 + 2
536  *      version        INTEGER ,                1 + 1 + 1
537  *      privateKey     OCTET STRING,            1 + 1 + ECP_MAX
538  *      parameters [0] ECParameters OPTIONAL,   1 + 1 + (1 + 1 + 9)
539  *      publicKey  [1] BIT STRING OPTIONAL      1 + 2 + [1] above
540  *    }
541  */
542 #define ECP_PRV_DER_MAX_BYTES   ( 29 + 3 * MBEDTLS_ECP_MAX_BYTES )
543 
544 #else /* MBEDTLS_ECP_C */
545 
546 #define ECP_PUB_DER_MAX_BYTES   0
547 #define ECP_PRV_DER_MAX_BYTES   0
548 
549 #endif /* MBEDTLS_ECP_C */
550 
551 #define PUB_DER_MAX_BYTES   ( RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
552                               RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES )
553 #define PRV_DER_MAX_BYTES   ( RSA_PRV_DER_MAX_BYTES > ECP_PRV_DER_MAX_BYTES ? \
554                               RSA_PRV_DER_MAX_BYTES : ECP_PRV_DER_MAX_BYTES )
555 
mbedtls_pk_write_pubkey_pem(const mbedtls_pk_context * key,unsigned char * buf,size_t size)556 int mbedtls_pk_write_pubkey_pem( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
557 {
558     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
559     unsigned char output_buf[PUB_DER_MAX_BYTES];
560     size_t olen = 0;
561 
562     PK_VALIDATE_RET( key != NULL );
563     PK_VALIDATE_RET( buf != NULL || size == 0 );
564 
565     if( ( ret = mbedtls_pk_write_pubkey_der( key, output_buf,
566                                      sizeof(output_buf) ) ) < 0 )
567     {
568         return( ret );
569     }
570 
571     if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_PUBLIC_KEY, PEM_END_PUBLIC_KEY,
572                                   output_buf + sizeof(output_buf) - ret,
573                                   ret, buf, size, &olen ) ) != 0 )
574     {
575         return( ret );
576     }
577 
578     return( 0 );
579 }
580 
mbedtls_pk_write_key_pem(const mbedtls_pk_context * key,unsigned char * buf,size_t size)581 int mbedtls_pk_write_key_pem( const mbedtls_pk_context *key, unsigned char *buf, size_t size )
582 {
583     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
584     unsigned char output_buf[PRV_DER_MAX_BYTES];
585     const char *begin, *end;
586     size_t olen = 0;
587 
588     PK_VALIDATE_RET( key != NULL );
589     PK_VALIDATE_RET( buf != NULL || size == 0 );
590 
591     if( ( ret = mbedtls_pk_write_key_der( key, output_buf, sizeof(output_buf) ) ) < 0 )
592         return( ret );
593 
594 #if defined(MBEDTLS_RSA_C)
595     if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )
596     {
597         begin = PEM_BEGIN_PRIVATE_KEY_RSA;
598         end = PEM_END_PRIVATE_KEY_RSA;
599     }
600     else
601 #endif
602 #if defined(MBEDTLS_ECP_C)
603     if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )
604     {
605         begin = PEM_BEGIN_PRIVATE_KEY_EC;
606         end = PEM_END_PRIVATE_KEY_EC;
607     }
608     else
609 #endif
610         return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
611 
612     if( ( ret = mbedtls_pem_write_buffer( begin, end,
613                                   output_buf + sizeof(output_buf) - ret,
614                                   ret, buf, size, &olen ) ) != 0 )
615     {
616         return( ret );
617     }
618 
619     return( 0 );
620 }
621 #endif /* MBEDTLS_PEM_WRITE_C */
622 
623 #endif /* MBEDTLS_PK_WRITE_C */
624