Debian Codegraph @

src/ltc/pk/asn1/der/object_identifier/der_length_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_length_object_identifier.c
7 ASN.1 DER, get length of Object Identifier, Tom St Denis
8 */
9
10 #ifdef LTC_DER
11
12 static LTC_INLINE unsigned long s_der_object_identifier_bits(unsigned long x)
13 {
14 #if defined(LTC_HAVE_CLZL_BUILTIN)
15 if (x == 0)
16 return 0;
17 return sizeof(unsigned long) * CHAR_BIT - __builtin_clzl(x);
18 #else
19 unsigned long c;
20 c = 0;
21 while (x) {
22 ++c;
23 x >>= 1;
24 }
25 return c;
26 #endif
27 }
28
29 int der_length_object_identifier_full(const unsigned long *words, unsigned long nwords, unsigned long *outlen, unsigned long *datalen)
30 {
31 unsigned long y, z, t, wordbuf;
32
33 LTC_ARGCHK(words != NULL);
34 LTC_ARGCHK(outlen != NULL);
35
36
37 /* must be >= 2 words */
38 if (nwords < 2) {
39 return CRYPT_INVALID_ARG;
40 }
41
42 /* word1 = 0,1,2 and word2 0..39 */
43 if (words[0] > 2 || (words[0] < 2 && words[1] > 39)) {
44 return CRYPT_INVALID_ARG;
45 }
46
47 /* leading word is the first two */
48 z = 0;
49 wordbuf = words[0] * 40 + words[1];
50 for (y = 1; y < nwords; y++) {
51 t = s_der_object_identifier_bits(wordbuf);
52 z += t/7 + ((t%7) ? 1 : 0) + (wordbuf == 0 ? 1 : 0);
53 if (y < nwords - 1) {
54 /* grab next word */
55 wordbuf = words[y+1];
56 }
57 }
58
59 if (datalen) {
60 *datalen = z;
61 }
62 /* now depending on the length our length encoding changes */
63 if (z < 128) {
64 z += 2;
65 } else if (z < 256) {
66 z += 3;
67 } else if (z < 65536UL) {
68 z += 4;
69 } else {
70 return CRYPT_INVALID_ARG;
71 }
72
73 *outlen = z;
74 return CRYPT_OK;
75 }
76
77 /**
78 Gets length of DER encoding of Object Identifier
79 @param nwords The number of OID words
80 @param words The actual OID words to get the size of
81 @param outlen [out] The length of the DER encoding for the given string
82 @return CRYPT_OK if successful
83 */
84 int der_length_object_identifier(const unsigned long *words, unsigned long nwords, unsigned long *outlen)
85 {
86 return der_length_object_identifier_full(words, nwords, outlen, NULL);
87 }
88
89 #endif