]> pd.if.org Git - zpackage/blob - libtomcrypt/src/pk/asn1/der/short_integer/der_encode_short_integer.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / pk / asn1 / der / short_integer / der_encode_short_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_encode_short_integer.c
13   ASN.1 DER, encode an integer, Tom St Denis
14 */
15
16
17 #ifdef LTC_DER
18
19 /**
20   Store a short integer in the range (0,2^32-1)
21   @param num      The integer to encode
22   @param out      [out] The destination for the DER encoded integers
23   @param outlen   [in/out] The max size and resulting size of the DER encoded integers
24   @return CRYPT_OK if successful
25 */
26 int der_encode_short_integer(unsigned long num, unsigned char *out, unsigned long *outlen)
27 {
28    unsigned long len, x, y, z;
29    int           err;
30
31    LTC_ARGCHK(out    != NULL);
32    LTC_ARGCHK(outlen != NULL);
33
34    /* force to 32 bits */
35    num &= 0xFFFFFFFFUL;
36
37    /* find out how big this will be */
38    if ((err = der_length_short_integer(num, &len)) != CRYPT_OK) {
39       return err;
40    }
41
42    if (*outlen < len) {
43       *outlen = len;
44       return CRYPT_BUFFER_OVERFLOW;
45    }
46
47    /* get len of output */
48    z = 0;
49    y = num;
50    while (y) {
51      ++z;
52      y >>= 8;
53    }
54
55    /* handle zero */
56    if (z == 0) {
57       z = 1;
58    }
59
60    /* see if msb is set */
61    z += (num&(1UL<<((z<<3) - 1))) ? 1 : 0;
62
63    /* adjust the number so the msB is non-zero */
64    for (x = 0; (z <= 4) && (x < (4 - z)); x++) {
65       num <<= 8;
66    }
67
68    /* store header */
69    x = 0;
70    out[x++] = 0x02;
71    out[x++] = (unsigned char)z;
72
73    /* if 31st bit is set output a leading zero and decrement count */
74    if (z == 5) {
75       out[x++] = 0;
76       --z;
77    }
78
79    /* store values */
80    for (y = 0; y < z; y++) {
81       out[x++] = (unsigned char)((num >> 24) & 0xFF);
82       num    <<= 8;
83    }
84
85    /* we good */
86    *outlen = x;
87
88    return CRYPT_OK;
89 }
90
91 #endif
92
93 /* ref:         $Format:%D$ */
94 /* git commit:  $Format:%H$ */
95 /* commit time: $Format:%ai$ */