]> pd.if.org Git - zpackage/blob - libtomcrypt/src/pk/asn1/der/integer/der_length_integer.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / pk / asn1 / der / integer / der_length_integer.c
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 #include "tomcrypt.h"
10
11 /**
12   @file der_length_integer.c
13   ASN.1 DER, get length of encoding, Tom St Denis
14 */
15
16
17 #ifdef LTC_DER
18 /**
19   Gets length of DER encoding of num
20   @param num    The int to get the size of
21   @param outlen [out] The length of the DER encoding for the given integer
22   @return CRYPT_OK if successful
23 */
24 int der_length_integer(void *num, unsigned long *outlen)
25 {
26    unsigned long z, len;
27    int           leading_zero;
28
29    LTC_ARGCHK(num     != NULL);
30    LTC_ARGCHK(outlen  != NULL);
31
32    if (mp_cmp_d(num, 0) != LTC_MP_LT) {
33       /* positive */
34
35       /* we only need a leading zero if the msb of the first byte is one */
36       if ((mp_count_bits(num) & 7) == 0 || mp_iszero(num) == LTC_MP_YES) {
37          leading_zero = 1;
38       } else {
39          leading_zero = 0;
40       }
41
42       /* size for bignum */
43       z = len = leading_zero + mp_unsigned_bin_size(num);
44    } else {
45       /* it's negative */
46       /* find power of 2 that is a multiple of eight and greater than count bits */
47       z = mp_count_bits(num);
48       z = z + (8 - (z & 7));
49       if (((mp_cnt_lsb(num)+1)==mp_count_bits(num)) && ((mp_count_bits(num)&7)==0)) --z;
50       len = z = z >> 3;
51    }
52
53    /* now we need a length */
54    if (z < 128) {
55       /* short form */
56       ++len;
57    } else {
58       /* long form (relies on z != 0), assumes length bytes < 128 */
59       ++len;
60
61       while (z) {
62          ++len;
63          z >>= 8;
64       }
65    }
66
67    /* we need a 0x02 to indicate it's INTEGER */
68    ++len;
69
70    /* return length */
71    *outlen = len;
72    return CRYPT_OK;
73 }
74
75 #endif
76
77 /* ref:         $Format:%D$ */
78 /* git commit:  $Format:%H$ */
79 /* commit time: $Format:%ai$ */