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_decode_integer.c
13 ASN.1 DER, decode an integer, Tom St Denis
21 @param in The DER encoded data
22 @param inlen Size of DER encoded data
23 @param num The first mp_int to decode
24 @return CRYPT_OK if successful
26 int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num)
28 unsigned long x, y, z;
31 LTC_ARGCHK(num != NULL);
32 LTC_ARGCHK(in != NULL);
34 /* min DER INTEGER is 0x02 01 00 == 0 */
35 if (inlen < (1 + 1 + 1)) {
36 return CRYPT_INVALID_PACKET;
39 /* ok expect 0x02 when we AND with 0001 1111 [1F] */
41 if ((in[x++] & 0x1F) != 0x02) {
42 return CRYPT_INVALID_PACKET;
45 /* now decode the len stuff */
48 if ((z & 0x80) == 0x00) {
51 /* will it overflow? */
53 return CRYPT_INVALID_PACKET;
57 if ((err = mp_read_unsigned_bin(num, (unsigned char *)in + x, z)) != CRYPT_OK) {
64 /* will number of length bytes overflow? (or > 4) */
65 if (((x + z) > inlen) || (z > 4) || (z == 0)) {
66 return CRYPT_INVALID_PACKET;
72 y = ((unsigned long)(in[x++])) | (y << 8);
75 /* now will reading y bytes overrun? */
76 if ((x + y) > inlen) {
77 return CRYPT_INVALID_PACKET;
81 if ((err = mp_read_unsigned_bin(num, (unsigned char *)in + x, y)) != CRYPT_OK) {
86 /* see if it's negative */
89 if (mp_init(&tmp) != CRYPT_OK) {
93 if (mp_2expt(tmp, mp_count_bits(num)) != CRYPT_OK || mp_sub(num, tmp, num) != CRYPT_OK) {
106 /* ref: $Format:%D$ */
107 /* git commit: $Format:%H$ */
108 /* commit time: $Format:%ai$ */