1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
pk_oid_str_to_num(const char * OID,unsigned long * oid,unsigned long * oidlen)6 int pk_oid_str_to_num(const char *OID, unsigned long *oid, unsigned long *oidlen)
7 {
8    unsigned long i, j, limit, oid_j;
9    size_t OID_len;
10 
11    LTC_ARGCHK(oidlen != NULL);
12 
13    limit = *oidlen;
14    *oidlen = 0; /* make sure that we return zero oidlen on error */
15    for (i = 0; i < limit; i++) oid[i] = 0;
16 
17    if (OID == NULL) return CRYPT_OK;
18 
19    OID_len = XSTRLEN(OID);
20    if (OID_len == 0) return CRYPT_OK;
21 
22    for (i = 0, j = 0; i < OID_len; i++) {
23       if (OID[i] == '.') {
24          if (++j >= limit) continue;
25       }
26       else if ((OID[i] >= '0') && (OID[i] <= '9')) {
27          if ((j >= limit) || (oid == NULL)) continue;
28          oid_j = oid[j];
29          oid[j] = oid[j] * 10 + (OID[i] - '0');
30          if (oid[j] < oid_j) return CRYPT_OVERFLOW;
31       }
32       else {
33          return CRYPT_ERROR;
34       }
35    }
36    if (j == 0) return CRYPT_ERROR;
37    if (j >= limit) {
38       *oidlen = j;
39       return CRYPT_BUFFER_OVERFLOW;
40    }
41    *oidlen = j + 1;
42    return CRYPT_OK;
43 }
44 
pk_oid_num_to_str(const unsigned long * oid,unsigned long oidlen,char * OID,unsigned long * outlen)45 int pk_oid_num_to_str(const unsigned long *oid, unsigned long oidlen, char *OID, unsigned long *outlen)
46 {
47    int i;
48    unsigned long j, k;
49    char tmp[256] = { 0 };
50 
51    LTC_ARGCHK(oid != NULL);
52    LTC_ARGCHK(oidlen < INT_MAX);
53    LTC_ARGCHK(outlen != NULL);
54 
55    for (i = oidlen - 1, k = 0; i >= 0; i--) {
56       j = oid[i];
57       if (j == 0) {
58          tmp[k] = '0';
59          if (++k >= sizeof(tmp)) return CRYPT_ERROR;
60       }
61       else {
62          while (j > 0) {
63             tmp[k] = '0' + (j % 10);
64             if (++k >= sizeof(tmp)) return CRYPT_ERROR;
65             j /= 10;
66          }
67       }
68       if (i > 0) {
69         tmp[k] = '.';
70         if (++k >= sizeof(tmp)) return CRYPT_ERROR;
71       }
72    }
73    if (*outlen < k + 1) {
74       *outlen = k + 1;
75       return CRYPT_BUFFER_OVERFLOW;
76    }
77    LTC_ARGCHK(OID != NULL);
78    for (j = 0; j < k; j++) OID[j] = tmp[k - j - 1];
79    OID[k] = '\0';
80    *outlen = k; /* the length without terminating NUL byte */
81    return CRYPT_OK;
82 }
83