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
9 * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com
14 @file der_decode_integer.c
15 ASN.1 DER, decode an integer, Tom St Denis
23 @param in The DER encoded data
24 @param inlen Size of DER encoded data
25 @param num The first mp_int to decode
26 @return CRYPT_OK if successful
28 int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num)
30 unsigned long x, y, z;
33 LTC_ARGCHK(num != NULL);
34 LTC_ARGCHK(in != NULL);
36 /* min DER INTEGER is 0x02 01 00 == 0 */
37 if (inlen < (1 + 1 + 1)) {
38 return CRYPT_INVALID_PACKET;
41 /* ok expect 0x02 when we AND with 0001 1111 [1F] */
43 if ((in[x++] & 0x1F) != 0x02) {
44 return CRYPT_INVALID_PACKET;
47 /* now decode the len stuff */
50 if ((z & 0x80) == 0x00) {
53 /* will it overflow? */
55 return CRYPT_INVALID_PACKET;
59 if ((err = mp_read_unsigned_bin(num, (unsigned char *)in + x, z)) != CRYPT_OK) {
66 /* will number of length bytes overflow? (or > 4) */
67 if (((x + z) > inlen) || (z > 4) || (z == 0)) {
68 return CRYPT_INVALID_PACKET;
74 y = ((unsigned long)(in[x++])) | (y << 8);
77 /* now will reading y bytes overrun? */
78 if ((x + y) > inlen) {
79 return CRYPT_INVALID_PACKET;
83 if ((err = mp_read_unsigned_bin(num, (unsigned char *)in + x, y)) != CRYPT_OK) {
88 /* see if it's negative */
91 if (mp_init(&tmp) != CRYPT_OK) {
95 if (mp_2expt(tmp, mp_count_bits(num)) != CRYPT_OK || mp_sub(num, tmp, num) != CRYPT_OK) {
108 /* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/integer/der_decode_integer.c,v $ */
109 /* $Revision: 1.4 $ */
110 /* $Date: 2006/03/31 14:15:35 $ */