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_length_short_integer.c
14   ASN.1 DER, get length of encoding, Tom St Denis
15 */
16 
17 
18 #ifdef LTC_DER
19 /**
20   Gets length of DER encoding of num
21   @param num    The integer to get the size of
22   @param outlen [out] The length of the DER encoding for the given integer
23   @return CRYPT_OK if successful
24 */
der_length_short_integer(unsigned long num,unsigned long * outlen)25 int der_length_short_integer(unsigned long num, unsigned long *outlen)
26 {
27    unsigned long z, y;
28    int err;
29 
30    LTC_ARGCHK(outlen  != NULL);
31 
32    /* force to 32 bits */
33    num &= 0xFFFFFFFFUL;
34 
35    /* get the number of bytes */
36    z = 0;
37    y = num;
38    while (y) {
39      ++z;
40      y >>= 8;
41    }
42 
43    /* handle zero */
44    if (z == 0) {
45       z = 1;
46    } else if ((num&(1UL<<((z<<3) - 1))) != 0) {
47       /* in case msb is set */
48       ++z;
49    }
50 
51    if ((err = der_length_asn1_length(z, &y)) != CRYPT_OK) {
52       return err;
53    }
54    *outlen = 1 + y + z;
55 
56    return CRYPT_OK;
57 }
58 
59 #endif
60 
61 /* ref:         $Format:%D$ */
62 /* git commit:  $Format:%H$ */
63 /* commit time: $Format:%ai$ */
64