1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2 *
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
5 *
6 * The library is free for all purposes without any express
7 * guarantee it works.
8 *
9 * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com
10 */
11 #include "tomcrypt.h"
12
13 /**
14 @file der_encode_octet_string.c
15 ASN.1 DER, encode a OCTET STRING, Tom St Denis
16 */
17
18
19 #ifdef LTC_DER
20
21 /**
22 Store an OCTET STRING
23 @param in The array of OCTETS to store (one per char)
24 @param inlen The number of OCTETS to store
25 @param out [out] The destination for the DER encoded OCTET STRING
26 @param outlen [in/out] The max size and resulting size of the DER OCTET STRING
27 @return CRYPT_OK if successful
28 */
der_encode_octet_string(const unsigned char * in,unsigned long inlen,unsigned char * out,unsigned long * outlen)29 int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
30 unsigned char *out, unsigned long *outlen)
31 {
32 unsigned long x, y, len;
33 int err;
34
35 LTC_ARGCHK(in != NULL);
36 LTC_ARGCHK(out != NULL);
37 LTC_ARGCHK(outlen != NULL);
38
39 /* get the size */
40 if ((err = der_length_octet_string(inlen, &len)) != CRYPT_OK) {
41 return err;
42 }
43
44 /* too big? */
45 if (len > *outlen) {
46 *outlen = len;
47 return CRYPT_BUFFER_OVERFLOW;
48 }
49
50 /* encode the header+len */
51 x = 0;
52 out[x++] = 0x04;
53 if (inlen < 128) {
54 out[x++] = (unsigned char)inlen;
55 } else if (inlen < 256) {
56 out[x++] = 0x81;
57 out[x++] = (unsigned char)inlen;
58 } else if (inlen < 65536UL) {
59 out[x++] = 0x82;
60 out[x++] = (unsigned char)((inlen>>8)&255);
61 out[x++] = (unsigned char)(inlen&255);
62 } else if (inlen < 16777216UL) {
63 out[x++] = 0x83;
64 out[x++] = (unsigned char)((inlen>>16)&255);
65 out[x++] = (unsigned char)((inlen>>8)&255);
66 out[x++] = (unsigned char)(inlen&255);
67 } else {
68 return CRYPT_INVALID_ARG;
69 }
70
71 /* store octets */
72 for (y = 0; y < inlen; y++) {
73 out[x++] = in[y];
74 }
75
76 /* retun length */
77 *outlen = x;
78
79 return CRYPT_OK;
80 }
81
82 #endif
83
84 /* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/octet/der_encode_octet_string.c,v $ */
85 /* $Revision: 1.4 $ */
86 /* $Date: 2006/12/04 21:34:03 $ */
87