| 1 |
/* LibTomCrypt, modular cryptographic library -- Tom St Denis */ |
| 2 |
/* SPDX-License-Identifier: Unlicense */ |
| 3 |
#include "tomcrypt_private.h" |
| 4 |
|
| 5 |
/** |
| 6 |
@file der_decode_bit_string.c |
| 7 |
ASN.1 DER, encode a BIT STRING, Tom St Denis |
| 8 |
*/ |
| 9 |
|
| 10 |
|
| 11 |
#ifdef LTC_DER |
| 12 |
|
| 13 |
/** |
| 14 |
Store a BIT STRING |
| 15 |
@param in The DER encoded BIT STRING |
| 16 |
@param inlen The size of the DER BIT STRING |
| 17 |
@param out [out] The array of bits stored (one per char) |
| 18 |
@param outlen [in/out] The number of bits stored |
| 19 |
@return CRYPT_OK if successful |
| 20 |
*/ |
| 21 |
int der_decode_bit_string(const unsigned char *in, unsigned long inlen, |
| 22 |
unsigned char *out, unsigned long *outlen) |
| 23 |
{ |
| 24 |
unsigned long dlen, blen, x, y, unused; |
| 25 |
int err; |
| 26 |
|
| 27 |
LTC_ARGCHK(in != NULL); |
| 28 |
LTC_ARGCHK(out != NULL); |
| 29 |
LTC_ARGCHK(outlen != NULL); |
| 30 |
|
| 31 |
/* packet must be at least 3 bytes */ |
| 32 |
if (inlen < 3) { |
| 33 |
return CRYPT_INVALID_ARG; |
| 34 |
} |
| 35 |
|
| 36 |
/* check for 0x03 */ |
| 37 |
if ((in[0]&0x1F) != 0x03) { |
| 38 |
return CRYPT_INVALID_PACKET; |
| 39 |
} |
| 40 |
|
| 41 |
/* offset in the data */ |
| 42 |
x = 1; |
| 43 |
|
| 44 |
/* get the length of the data */ |
| 45 |
y = inlen - 1; |
| 46 |
if ((err = der_decode_asn1_length(in + x, &y, &dlen)) != CRYPT_OK) { |
| 47 |
return err; |
| 48 |
} |
| 49 |
x += y; |
| 50 |
/* is the data len too long or too short? */ |
| 51 |
if ((dlen == 0) || (dlen > (inlen - x))) { |
| 52 |
return CRYPT_INVALID_PACKET; |
| 53 |
} |
| 54 |
|
| 55 |
/* DER permits 0..7 unused bits, and any declared padding bits must be zero. */ |
| 56 |
unused = in[x]; |
| 57 |
if (unused > 7) { |
| 58 |
return CRYPT_INVALID_PACKET; |
| 59 |
} |
| 60 |
if ((dlen == 1) && (unused != 0)) { |
| 61 |
return CRYPT_INVALID_PACKET; |
| 62 |
} |
| 63 |
if ((unused != 0) && ((in[x + dlen - 1] & ((1uL << unused) - 1uL)) != 0)) { |
| 64 |
return CRYPT_INVALID_PACKET; |
| 65 |
} |
| 66 |
x++; |
| 67 |
blen = ((dlen - 1) << 3) - unused; |
| 68 |
|
| 69 |
/* too many bits? */ |
| 70 |
if (blen > *outlen) { |
| 71 |
*outlen = blen; |
| 72 |
return CRYPT_BUFFER_OVERFLOW; |
| 73 |
} |
| 74 |
|
| 75 |
/* decode/store the bits */ |
| 76 |
for (y = 0; y < blen; y++) { |
| 77 |
out[y] = (in[x] & (1 << (7 - (y & 7)))) ? 1 : 0; |
| 78 |
if ((y & 7) == 7) { |
| 79 |
++x; |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
/* we done */ |
| 84 |
*outlen = blen; |
| 85 |
return CRYPT_OK; |
| 86 |
} |
| 87 |
|
| 88 |
#endif |