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.org
14
@file der_encode_integer.c
15
ASN.1 DER, encode an integer, Tom St Denis
21
/* Exports a positive bignum as DER format (upto 2^32 bytes in size) */
23
Store a mp_int integer
24
@param num The first mp_int to encode
25
@param out [out] The destination for the DER encoded integers
26
@param outlen [in/out] The max size and resulting size of the DER encoded integers
27
@return CRYPT_OK if successful
29
int der_encode_integer(mp_int *num, unsigned char *out, unsigned long *outlen)
31
unsigned long tmplen, y;
32
int err, leading_zero;
34
LTC_ARGCHK(num != NULL);
35
LTC_ARGCHK(out != NULL);
36
LTC_ARGCHK(outlen != NULL);
38
/* find out how big this will be */
39
if ((err = der_length_integer(num, &tmplen)) != CRYPT_OK) {
43
if (*outlen < tmplen) {
44
return CRYPT_BUFFER_OVERFLOW;
47
if (mp_cmp_d(num, 0) != MP_LT) {
48
/* we only need a leading zero if the msb of the first byte is one */
49
if ((mp_count_bits(num) & 7) == 0 || mp_iszero(num) == MP_YES) {
55
/* get length of num in bytes (plus 1 since we force the msbyte to zero) */
56
y = mp_unsigned_bin_size(num) + leading_zero;
59
y = mp_count_bits(num);
60
y = y + (8 - (y & 7));
65
/* now store initial data */
69
*out++ = (unsigned char)y;
73
} else if (y < 65536UL) {
77
} else if (y < 16777216UL) {
83
return CRYPT_INVALID_ARG;
86
/* now store msbyte of zero if num is non-zero */
91
/* if it's not zero store it as big endian */
92
if (mp_cmp_d(num, 0) == MP_GT) {
93
/* now store the mpint */
94
if ((err = mp_to_unsigned_bin(num, out)) != MP_OKAY) {
95
return mpi_to_ltc_error(err);
97
} else if (mp_iszero(num) != MP_YES) {
100
if (mp_init(&tmp) != MP_OKAY) {
104
/* 2^roundup and subtract */
105
y = mp_count_bits(num);
106
y = y + (8 - (y & 7));
107
if (mp_2expt(&tmp, y) != MP_OKAY || mp_add(&tmp, num, &tmp) != MP_OKAY) {
112
if ((err = mp_to_unsigned_bin(&tmp, out)) != MP_OKAY) {
114
return mpi_to_ltc_error(err);
126
/* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/integer/der_encode_integer.c,v $ */
127
/* $Revision: 1.1 $ */
128
/* $Date: 2005/05/16 15:08:11 $ */