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_encode_short_integer.c
13 ASN.1 DER, encode an integer, Tom St Denis
20 Store a short integer in the range (0,2^32-1)
21 @param num The integer to encode
22 @param out [out] The destination for the DER encoded integers
23 @param outlen [in/out] The max size and resulting size of the DER encoded integers
24 @return CRYPT_OK if successful
26 int der_encode_short_integer(unsigned long num, unsigned char *out, unsigned long *outlen)
28 unsigned long len, x, y, z;
31 LTC_ARGCHK(out != NULL);
32 LTC_ARGCHK(outlen != NULL);
34 /* force to 32 bits */
37 /* find out how big this will be */
38 if ((err = der_length_short_integer(num, &len)) != CRYPT_OK) {
44 return CRYPT_BUFFER_OVERFLOW;
47 /* get len of output */
60 /* see if msb is set */
61 z += (num&(1UL<<((z<<3) - 1))) ? 1 : 0;
63 /* adjust the number so the msB is non-zero */
64 for (x = 0; (z <= 4) && (x < (4 - z)); x++) {
71 out[x++] = (unsigned char)z;
73 /* if 31st bit is set output a leading zero and decrement count */
80 for (y = 0; y < z; y++) {
81 out[x++] = (unsigned char)((num >> 24) & 0xFF);
93 /* ref: $Format:%D$ */
94 /* git commit: $Format:%H$ */
95 /* commit time: $Format:%ai$ */