1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
12 @file der_encode_bit_string.c
13 ASN.1 DER, encode a BIT STRING, Tom St Denis
19 #define getbit(n, k) (((n) & ( 1 << (k) )) >> (k))
23 @param in The array of bits to store (8 per char)
24 @param inlen The number of bits to store
25 @param out [out] The destination for the DER encoded BIT STRING
26 @param outlen [in/out] The max size and resulting size of the DER BIT STRING
27 @return CRYPT_OK if successful
29 int der_encode_raw_bit_string(const unsigned char *in, unsigned long inlen,
30 unsigned char *out, unsigned long *outlen)
32 unsigned long len, x, y;
36 LTC_ARGCHK(in != NULL);
37 LTC_ARGCHK(out != NULL);
38 LTC_ARGCHK(outlen != NULL);
41 if ((err = der_length_bit_string(inlen, &len)) != CRYPT_OK) {
47 return CRYPT_BUFFER_OVERFLOW;
50 /* store header (include bit padding count in length) */
52 y = (inlen >> 3) + ((inlen&7) ? 1 : 0) + 1;
56 out[x++] = (unsigned char)y;
59 out[x++] = (unsigned char)y;
60 } else if (y < 65536) {
62 out[x++] = (unsigned char)((y>>8)&255);
63 out[x++] = (unsigned char)(y&255);
66 /* store number of zero padding bits */
67 out[x++] = (unsigned char)((8 - inlen) & 7);
69 /* store the bits in big endian format */
70 for (y = buf = 0; y < inlen; y++) {
71 buf |= (getbit(in[y/8],7-y%8)?1:0) << (7 - (y & 7));
88 /* ref: $Format:%D$ */
89 /* git commit: $Format:%H$ */
90 /* commit time: $Format:%ai$ */