xref: /optee_os/core/lib/libtomcrypt/src/pk/ecc/ecc_ssh_ecdsa_encode_name.c (revision 8411e6ad673d20c4742ed30c785e3f5cdea54dfa)
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6    @file ecc_ssh_ecdsa_encode_name.c
7    Curve/OID to SSH+ECDSA name string mapping per RFC5656
8    Russ Williams
9 */
10 
11 #ifdef LTC_SSH
12 
13 /**
14   Curve/OID to SSH+ECDSA name string mapping
15   @param buffer    [out] The destination for the name
16   @param buflen    [in/out] The max size and resulting size (including terminator) of the name
17   @param key       A public or private ECC key
18   @return CRYPT_OK if successful
19 */
ecc_ssh_ecdsa_encode_name(char * buffer,unsigned long * buflen,const ecc_key * key)20 int ecc_ssh_ecdsa_encode_name(char *buffer, unsigned long *buflen, const ecc_key *key)
21 {
22    char oidstr[64] = {0};
23    unsigned long oidlen = sizeof(oidstr);
24    int err, size = 0;
25 
26    LTC_ARGCHK(buffer != NULL);
27    LTC_ARGCHK(buflen != NULL);
28    LTC_ARGCHK(key != NULL);
29 
30    /* Get the OID of the curve */
31    if ((err = ecc_get_oid_str(oidstr, &oidlen, key)) != CRYPT_OK) goto error;
32 
33    /* Check for three named curves: nistp256, nistp384, nistp521 */
34    if (XSTRCMP("1.2.840.10045.3.1.7", oidstr) == 0) {
35       /* nistp256 - secp256r1 - OID 1.2.840.10045.3.1.7 */
36       size = snprintf(buffer, *buflen, "ecdsa-sha2-nistp256");
37    }
38    else if (XSTRCMP("1.3.132.0.34", oidstr) == 0) {
39       /* nistp384 - secp384r1 - OID 1.3.132.0.34 */
40       size = snprintf(buffer, *buflen, "ecdsa-sha2-nistp384");
41    }
42    else if (XSTRCMP("1.3.132.0.35", oidstr) == 0) {
43       /* nistp521 - secp521r1 - OID 1.3.132.0.35 */
44       size = snprintf(buffer, *buflen, "ecdsa-sha2-nistp521");
45    } else {
46       /* Otherwise we use the OID... */
47       size = snprintf(buffer, *buflen, "ecdsa-sha2-%s", oidstr);
48    }
49 
50    /* snprintf returns a negative value on error
51     * or the size that would have been written, but limits to buflen-1 chars plus terminator */
52    if (size < 0) {
53       err = CRYPT_ERROR;
54    } else if ((unsigned)size >= *buflen) {
55       err = CRYPT_BUFFER_OVERFLOW;
56    } else {
57       err = CRYPT_OK;
58    }
59    *buflen = size + 1; /* the string length + NUL byte */
60 
61 error:
62    return err;
63 }
64 
65 #endif
66