comparison libtomcrypt/src/pk/asn1/der/bit/der_encode_bit_string.c @ 285:1b9e69c058d2

propagate from branch 'au.asn.ucc.matt.ltc.dropbear' (head 20dccfc09627970a312d77fb41dc2970b62689c3) to branch 'au.asn.ucc.matt.dropbear' (head fdf4a7a3b97ae5046139915de7e40399cceb2c01)
author Matt Johnston <matt@ucc.asn.au>
date Wed, 08 Mar 2006 13:23:58 +0000
parents
children 0cbe8f6dbf9e
comparison
equal deleted inserted replaced
281:997e6f7dc01e 285:1b9e69c058d2
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, [email protected], http://libtomcrypt.org
10 */
11 #include "tomcrypt.h"
12
13 /**
14 @file der_encode_bit_string.c
15 ASN.1 DER, encode a BIT STRING, Tom St Denis
16 */
17
18
19 #ifdef LTC_DER
20
21 /**
22 Store a BIT STRING
23 @param in The array of bits to store (one per char)
24 @param inlen The number of bits tostore
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
28 */
29 int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
30 unsigned char *out, unsigned long *outlen)
31 {
32 unsigned long len, x, y, buf;
33 int err;
34
35 LTC_ARGCHK(in != NULL);
36 LTC_ARGCHK(out != NULL);
37 LTC_ARGCHK(outlen != NULL);
38
39 /* avoid overflows */
40 if ((err = der_length_bit_string(inlen, &len)) != CRYPT_OK) {
41 return err;
42 }
43
44 if (len > *outlen) {
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++] = y;
55 } else if (y < 256) {
56 out[x++] = 0x81;
57 out[x++] = y;
58 } else if (y < 65536) {
59 out[x++] = 0x82;
60 out[x++] = (y>>8)&255;
61 out[x++] = y&255;
62 }
63
64 /* store number of zero padding bits */
65 out[x++] = (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 /* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/bit/der_encode_bit_string.c,v $ */
86 /* $Revision: 1.1 $ */
87 /* $Date: 2005/05/16 15:08:11 $ */