]> pd.if.org Git - zpackage/blob - libtomcrypt/src/pk/asn1/der/bit/der_encode_bit_string.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / pk / asn1 / der / bit / der_encode_bit_string.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_bit_string.c
13   ASN.1 DER, encode a BIT STRING, Tom St Denis
14 */
15
16
17 #ifdef LTC_DER
18
19 /**
20   Store a BIT STRING
21   @param in       The array of bits to store (one per char)
22   @param inlen    The number of bits tostore
23   @param out      [out] The destination for the DER encoded BIT STRING
24   @param outlen   [in/out] The max size and resulting size of the DER BIT STRING
25   @return CRYPT_OK if successful
26 */
27 int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
28                                 unsigned char *out, unsigned long *outlen)
29 {
30    unsigned long len, x, y;
31    unsigned char buf;
32    int           err;
33
34    LTC_ARGCHK(in     != NULL);
35    LTC_ARGCHK(out    != NULL);
36    LTC_ARGCHK(outlen != NULL);
37
38    /* avoid overflows */
39    if ((err = der_length_bit_string(inlen, &len)) != CRYPT_OK) {
40       return err;
41    }
42
43    if (len > *outlen) {
44       *outlen = len;
45       return CRYPT_BUFFER_OVERFLOW;
46    }
47
48    /* store header (include bit padding count in length) */
49    x = 0;
50    y = (inlen >> 3) + ((inlen&7) ? 1 : 0) + 1;
51
52    out[x++] = 0x03;
53    if (y < 128) {
54       out[x++] = (unsigned char)y;
55    } else if (y < 256) {
56       out[x++] = 0x81;
57       out[x++] = (unsigned char)y;
58    } else if (y < 65536) {
59       out[x++] = 0x82;
60       out[x++] = (unsigned char)((y>>8)&255);
61       out[x++] = (unsigned char)(y&255);
62    }
63
64    /* store number of zero padding bits */
65    out[x++] = (unsigned char)((8 - inlen) & 7);
66
67    /* store the bits in big endian format */
68    for (y = buf = 0; y < inlen; y++) {
69        buf |= (in[y] ? 1 : 0) << (7 - (y & 7));
70        if ((y & 7) == 7) {
71           out[x++] = buf;
72           buf      = 0;
73        }
74    }
75    /* store last byte */
76    if (inlen & 7) {
77       out[x++] = buf;
78    }
79    *outlen = x;
80    return CRYPT_OK;
81 }
82
83 #endif
84
85 /* ref:         $Format:%D$ */
86 /* git commit:  $Format:%H$ */
87 /* commit time: $Format:%ai$ */