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_encode_short_integer.c
15 ASN.1 DER, encode an integer, Tom St Denis
22 Store a short integer in the range (0,2^32-1)
23 @param num The integer to encode
24 @param out [out] The destination for the DER encoded integers
25 @param outlen [in/out] The max size and resulting size of the DER encoded integers
26 @return CRYPT_OK if successful
28 int der_encode_short_integer(unsigned long num, unsigned char *out, unsigned long *outlen)
30 unsigned long len, x, y, z;
33 LTC_ARGCHK(out != NULL);
34 LTC_ARGCHK(outlen != NULL);
36 /* force to 32 bits */
39 /* find out how big this will be */
40 if ((err = der_length_short_integer(num, &len)) != CRYPT_OK) {
46 return CRYPT_BUFFER_OVERFLOW;
49 /* get len of output */
62 /* see if msb is set */
63 z += (num&(1UL<<((z<<3) - 1))) ? 1 : 0;
65 /* adjust the number so the msB is non-zero */
66 for (x = 0; (z <= 4) && (x < (4 - z)); x++) {
73 out[x++] = (unsigned char)z;
75 /* if 31st bit is set output a leading zero and decrement count */
82 for (y = 0; y < z; y++) {
83 out[x++] = (unsigned char)((num >> 24) & 0xFF);
95 /* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/short_integer/der_encode_short_integer.c,v $ */
96 /* $Revision: 1.7 $ */
97 /* $Date: 2006/12/04 21:34:03 $ */