1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file der_decode_short_integer.c
7   ASN.1 DER, decode an integer, Tom St Denis
8 */
9 
10 
11 #ifdef LTC_DER
12 
13 /**
14   Read a short integer
15   @param in       The DER encoded data
16   @param inlen    Size of data
17   @param num      [out] The integer to decode
18   @return CRYPT_OK if successful
19 */
der_decode_short_integer(const unsigned char * in,unsigned long inlen,unsigned long * num)20 int der_decode_short_integer(const unsigned char *in, unsigned long inlen, unsigned long *num)
21 {
22    unsigned long len, x, y;
23 
24    LTC_ARGCHK(num    != NULL);
25    LTC_ARGCHK(in     != NULL);
26 
27    /* check length */
28    if (inlen < 2) {
29       return CRYPT_INVALID_PACKET;
30    }
31 
32    /* check header */
33    x = 0;
34    if ((in[x++] & 0x1F) != 0x02) {
35       return CRYPT_INVALID_PACKET;
36    }
37 
38    /* get the packet len */
39    len = in[x++];
40 
41    if (x + len > inlen) {
42       return CRYPT_INVALID_PACKET;
43    }
44 
45    if (len > sizeof(unsigned long)) {
46       return CRYPT_OVERFLOW;
47    }
48 
49    /* read number */
50    y = 0;
51    while (len--) {
52       y = (y<<8) | (unsigned long)in[x++];
53    }
54    *num = y;
55 
56    return CRYPT_OK;
57 
58 }
59 
60 #endif
61