1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3  *
4  * LibTomCrypt is a library that provides various cryptographic
5  * algorithms in a highly modular and flexible manner.
6  *
7  * The library is free for all purposes without any express
8  * guarantee it works.
9  */
10 #include "tomcrypt_private.h"
11 
12 /**
13   @file der_decode_integer.c
14   ASN.1 DER, decode an integer, Tom St Denis
15 */
16 
17 
18 #ifdef LTC_DER
19 
20 /**
21   Read a mp_int integer
22   @param in       The DER encoded data
23   @param inlen    Size of DER encoded data
24   @param num      The first mp_int to decode
25   @return CRYPT_OK if successful
26 */
der_decode_integer(const unsigned char * in,unsigned long inlen,void * num)27 int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num)
28 {
29    unsigned long x, y;
30    int           err;
31 
32    LTC_ARGCHK(num    != NULL);
33    LTC_ARGCHK(in     != NULL);
34 
35    /* min DER INTEGER is 0x02 01 00 == 0 */
36    if (inlen < (1 + 1 + 1)) {
37       return CRYPT_INVALID_PACKET;
38    }
39 
40    /* ok expect 0x02 when we AND with 0001 1111 [1F] */
41    x = 0;
42    if ((in[x++] & 0x1F) != 0x02) {
43       return CRYPT_INVALID_PACKET;
44    }
45 
46    /* get the length of the data */
47    inlen -= x;
48    if ((err = der_decode_asn1_length(in + x, &inlen, &y)) != CRYPT_OK) {
49       return err;
50    }
51    x += inlen;
52 
53    if ((err = mp_read_unsigned_bin(num, (unsigned char *)in + x, y)) != CRYPT_OK) {
54       return err;
55    }
56 
57    /* see if it's negative */
58    if (in[x] & 0x80) {
59       void *tmp;
60       if (mp_init(&tmp) != CRYPT_OK) {
61          return CRYPT_MEM;
62       }
63 
64       if (mp_2expt(tmp, mp_count_bits(num)) != CRYPT_OK || mp_sub(num, tmp, num) != CRYPT_OK) {
65          mp_clear(tmp);
66          return CRYPT_MEM;
67       }
68       mp_clear(tmp);
69    }
70 
71    return CRYPT_OK;
72 
73 }
74 
75 #endif
76 
77 /* ref:         $Format:%D$ */
78 /* git commit:  $Format:%H$ */
79 /* commit time: $Format:%ai$ */
80