1/* LibTomCrypt, modular cryptographic library -- Tom St Denis
2 *
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
5 *
6 * The library is free for all purposes without any express
7 * guarantee it works.
8 *
9 * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com
10 */
11#include "tomcrypt.h"
12
13/**
14  @file der_length_object_identifier.c
15  ASN.1 DER, get length of Object Identifier, Tom St Denis
16*/
17
18#ifdef LTC_DER
19
20unsigned long der_object_identifier_bits(unsigned long x)
21{
22   unsigned long c;
23   x &= 0xFFFFFFFF;
24   c  = 0;
25   while (x) {
26     ++c;
27     x >>= 1;
28   }
29   return c;
30}
31
32
33/**
34  Gets length of DER encoding of Object Identifier
35  @param nwords   The number of OID words
36  @param words    The actual OID words to get the size of
37  @param outlen   [out] The length of the DER encoding for the given string
38  @return CRYPT_OK if successful
39*/
40int der_length_object_identifier(unsigned long *words, unsigned long nwords, unsigned long *outlen)
41{
42   unsigned long y, z, t, wordbuf;
43
44   LTC_ARGCHK(words  != NULL);
45   LTC_ARGCHK(outlen != NULL);
46
47
48   /* must be >= 2 words */
49   if (nwords < 2) {
50      return CRYPT_INVALID_ARG;
51   }
52
53   /* word1 = 0,1,2,3 and word2 0..39 */
54   if (words[0] > 3 || (words[0] < 2 && words[1] > 39)) {
55      return CRYPT_INVALID_ARG;
56   }
57
58   /* leading word is the first two */
59   z = 0;
60   wordbuf = words[0] * 40 + words[1];
61   for (y = 1; y < nwords; y++) {
62       t = der_object_identifier_bits(wordbuf);
63       z += t/7 + ((t%7) ? 1 : 0) + (wordbuf == 0 ? 1 : 0);
64       if (y < nwords - 1) {
65          /* grab next word */
66          wordbuf = words[y+1];
67       }
68   }
69
70   /* now depending on the length our length encoding changes */
71   if (z < 128) {
72      z += 2;
73   } else if (z < 256) {
74      z += 3;
75   } else if (z < 65536UL) {
76      z += 4;
77   } else {
78      return CRYPT_INVALID_ARG;
79   }
80
81   *outlen = z;
82   return CRYPT_OK;
83}
84
85#endif
86
87/* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/object_identifier/der_length_object_identifier.c,v $ */
88/* $Revision: 1.4 $ */
89/* $Date: 2006/04/16 20:17:42 $ */
90