Debian Codegraph @

src/ltc/pk/asn1/der/object_identifier/der_encode_object_identifier.c

raw
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 */
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_full(words, nwords, &x, &z)) != CRYPT_OK) {
31 return err;
32 }
33 if (x > *outlen) {
34 *outlen = x;
35 return CRYPT_BUFFER_OVERFLOW;
36 }
37
38 /* store header + length */
39 x = 0;
40 out[x++] = 0x06;
41 y = *outlen - x;
42 if ((err = der_encode_asn1_length(z, out + x, &y)) != CRYPT_OK) {
43 return err;
44 }
45 x += y;
46
47 /* store first byte */
48 wordbuf = words[0] * 40 + words[1];
49 for (i = 1; i < nwords; i++) {
50 /* store 7 bit words in little endian */
51 t = wordbuf;
52 if (t) {
53 y = x;
54 mask = 0;
55 while (t) {
56 out[x++] = (unsigned char)((t & 0x7F) | mask);
57 t >>= 7;
58 mask |= 0x80; /* upper bit is set on all but the last byte */
59 }
60 /* now swap bytes y...x-1 */
61 z = x - 1;
62 while (y < z) {
63 t = out[y]; out[y] = out[z]; out[z] = (unsigned char)t;
64 ++y;
65 --z;
66 }
67 } else {
68 /* zero word */
69 out[x++] = 0x00;
70 }
71
72 if (i < nwords - 1) {
73 wordbuf = words[i + 1];
74 }
75 }
76
77 *outlen = x;
78 return CRYPT_OK;
79 }
80
81 #endif