1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file der_encode_object_identifier.c
7   ASN.1 DER, Encode Object Identifier, Tom St Denis
8 */
9 
10 #ifdef LTC_DER
11 /**
12   Encode an OID
13   @param words   The words to encode  (upto 32-bits each)
14   @param nwords  The number of words in the OID
15   @param out     [out] Destination of OID data
16   @param outlen  [in/out] The max and resulting size of the OID
17   @return CRYPT_OK if successful
18 */
der_encode_object_identifier(const unsigned long * words,unsigned long nwords,unsigned char * out,unsigned long * outlen)19 int der_encode_object_identifier(const unsigned long *words, unsigned long  nwords,
20                                        unsigned char *out,   unsigned long *outlen)
21 {
22    unsigned long i, x, y, z, t, mask, wordbuf;
23    int           err;
24 
25    LTC_ARGCHK(words  != NULL);
26    LTC_ARGCHK(out    != NULL);
27    LTC_ARGCHK(outlen != NULL);
28 
29    /* check length */
30    if ((err = der_length_object_identifier(words, nwords, &x)) != CRYPT_OK) {
31       return err;
32    }
33    if (x > *outlen) {
34       *outlen = x;
35       return CRYPT_BUFFER_OVERFLOW;
36    }
37 
38    /* compute length to store OID data */
39    z = 0;
40    wordbuf = words[0] * 40 + words[1];
41    for (y = 1; y < nwords; y++) {
42        t = der_object_identifier_bits(wordbuf);
43        z += t/7 + ((t%7) ? 1 : 0) + (wordbuf == 0 ? 1 : 0);
44        if (y < nwords - 1) {
45           wordbuf = words[y + 1];
46        }
47    }
48 
49    /* store header + length */
50    x = 0;
51    out[x++] = 0x06;
52    y = *outlen - x;
53    if ((err = der_encode_asn1_length(z, out + x, &y)) != CRYPT_OK) {
54       return err;
55    }
56    x += y;
57 
58    /* store first byte */
59    wordbuf = words[0] * 40 + words[1];
60    for (i = 1; i < nwords; i++) {
61       /* store 7 bit words in little endian */
62       t    = wordbuf & 0xFFFFFFFF;
63       if (t) {
64          y    = x;
65          mask = 0;
66          while (t) {
67             out[x++] = (unsigned char)((t & 0x7F) | mask);
68             t    >>= 7;
69             mask  |= 0x80;  /* upper bit is set on all but the last byte */
70          }
71          /* now swap bytes y...x-1 */
72          z = x - 1;
73          while (y < z) {
74             t = out[y]; out[y] = out[z]; out[z] = (unsigned char)t;
75             ++y;
76             --z;
77          }
78       } else {
79          /* zero word */
80          out[x++] = 0x00;
81       }
82 
83       if (i < nwords - 1) {
84          wordbuf = words[i + 1];
85       }
86    }
87 
88    *outlen = x;
89    return CRYPT_OK;
90 }
91 
92 #endif
93