]> pd.if.org Git - zpackage/blob - libtomcrypt/src/pk/asn1/der/octet/der_encode_octet_string.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / pk / asn1 / der / octet / der_encode_octet_string.c
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 #include "tomcrypt.h"
10
11 /**
12   @file der_encode_octet_string.c
13   ASN.1 DER, encode a OCTET STRING, Tom St Denis
14 */
15
16
17 #ifdef LTC_DER
18
19 /**
20   Store an OCTET STRING
21   @param in       The array of OCTETS to store (one per char)
22   @param inlen    The number of OCTETS to store
23   @param out      [out] The destination for the DER encoded OCTET STRING
24   @param outlen   [in/out] The max size and resulting size of the DER OCTET STRING
25   @return CRYPT_OK if successful
26 */
27 int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
28                                   unsigned char *out, unsigned long *outlen)
29 {
30    unsigned long x, y, len;
31    int           err;
32
33    LTC_ARGCHK(in     != NULL);
34    LTC_ARGCHK(out    != NULL);
35    LTC_ARGCHK(outlen != NULL);
36
37    /* get the size */
38    if ((err = der_length_octet_string(inlen, &len)) != CRYPT_OK) {
39       return err;
40    }
41
42    /* too big? */
43    if (len > *outlen) {
44       *outlen = len;
45       return CRYPT_BUFFER_OVERFLOW;
46    }
47
48    /* encode the header+len */
49    x = 0;
50    out[x++] = 0x04;
51    if (inlen < 128) {
52       out[x++] = (unsigned char)inlen;
53    } else if (inlen < 256) {
54       out[x++] = 0x81;
55       out[x++] = (unsigned char)inlen;
56    } else if (inlen < 65536UL) {
57       out[x++] = 0x82;
58       out[x++] = (unsigned char)((inlen>>8)&255);
59       out[x++] = (unsigned char)(inlen&255);
60    } else if (inlen < 16777216UL) {
61       out[x++] = 0x83;
62       out[x++] = (unsigned char)((inlen>>16)&255);
63       out[x++] = (unsigned char)((inlen>>8)&255);
64       out[x++] = (unsigned char)(inlen&255);
65    } else {
66       return CRYPT_INVALID_ARG;
67    }
68
69    /* store octets */
70    for (y = 0; y < inlen; y++) {
71        out[x++] = in[y];
72    }
73
74    /* retun length */
75    *outlen = x;
76
77    return CRYPT_OK;
78 }
79
80 #endif
81
82 /* ref:         $Format:%D$ */
83 /* git commit:  $Format:%H$ */
84 /* commit time: $Format:%ai$ */