1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3  *
4  * LibTomCrypt is a library that provides various cryptographic
5  * algorithms in a highly modular and flexible manner.
6  *
7  * The library is free for all purposes without any express
8  * guarantee it works.
9  */
10 
11 #include "tomcrypt_private.h"
12 
pk_oid_str_to_num(const char * OID,unsigned long * oid,unsigned long * oidlen)13 int pk_oid_str_to_num(const char *OID, unsigned long *oid, unsigned long *oidlen)
14 {
15    unsigned long i, j, limit, OID_len, oid_j;
16 
17    LTC_ARGCHK(oidlen != NULL);
18 
19    limit = *oidlen;
20    *oidlen = 0; /* make sure that we return zero oidlen on error */
21    for (i = 0; i < limit; i++) oid[i] = 0;
22 
23    if (OID == NULL) return CRYPT_OK;
24 
25    OID_len = strlen(OID);
26    if (OID_len == 0) return CRYPT_OK;
27 
28    for (i = 0, j = 0; i < OID_len; i++) {
29       if (OID[i] == '.') {
30          if (++j >= limit) continue;
31       }
32       else if ((OID[i] >= '0') && (OID[i] <= '9')) {
33          if ((j >= limit) || (oid == NULL)) continue;
34          oid_j = oid[j];
35          oid[j] = oid[j] * 10 + (OID[i] - '0');
36          if (oid[j] < oid_j) return CRYPT_OVERFLOW;
37       }
38       else {
39          return CRYPT_ERROR;
40       }
41    }
42    if (j == 0) return CRYPT_ERROR;
43    if (j >= limit) {
44       *oidlen = j;
45       return CRYPT_BUFFER_OVERFLOW;
46    }
47    *oidlen = j + 1;
48    return CRYPT_OK;
49 }
50 
pk_oid_num_to_str(const unsigned long * oid,unsigned long oidlen,char * OID,unsigned long * outlen)51 int pk_oid_num_to_str(const unsigned long *oid, unsigned long oidlen, char *OID, unsigned long *outlen)
52 {
53    int i;
54    unsigned long j, k;
55    char tmp[256] = { 0 };
56 
57    LTC_ARGCHK(oid != NULL);
58    LTC_ARGCHK(OID != NULL);
59    LTC_ARGCHK(outlen != NULL);
60 
61    for (i = oidlen - 1, k = 0; i >= 0; i--) {
62       j = oid[i];
63       if (j == 0) {
64          tmp[k] = '0';
65          if (++k >= sizeof(tmp)) return CRYPT_ERROR;
66       }
67       else {
68          while (j > 0) {
69             tmp[k] = '0' + (j % 10);
70             if (++k >= sizeof(tmp)) return CRYPT_ERROR;
71             j /= 10;
72          }
73       }
74       if (i > 0) {
75         tmp[k] = '.';
76         if (++k >= sizeof(tmp)) return CRYPT_ERROR;
77       }
78    }
79    if (*outlen < k + 1) {
80       *outlen = k + 1;
81       return CRYPT_BUFFER_OVERFLOW;
82    }
83    for (j = 0; j < k; j++) OID[j] = tmp[k - j - 1];
84    OID[k] = '\0';
85    *outlen = k; /* the length without terminating NUL byte */
86    return CRYPT_OK;
87 }
88 
89 /* ref:         $Format:%D$ */
90 /* git commit:  $Format:%H$ */
91 /* commit time: $Format:%ai$ */
92