1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4
5 /**
6 @file der_encode_octet_string.c
7 ASN.1 DER, encode a OCTET STRING, Tom St Denis
8 */
9
10
11 #ifdef LTC_DER
12
13 /**
14 Store an OCTET STRING
15 @param in The array of OCTETS to store (one per char)
16 @param inlen The number of OCTETS to store
17 @param out [out] The destination for the DER encoded OCTET STRING
18 @param outlen [in/out] The max size and resulting size of the DER OCTET STRING
19 @return CRYPT_OK if successful
20 */
der_encode_octet_string(const unsigned char * in,unsigned long inlen,unsigned char * out,unsigned long * outlen)21 int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
22 unsigned char *out, unsigned long *outlen)
23 {
24 unsigned long x, y, len;
25 int err;
26
27 LTC_ARGCHK(in != NULL);
28 LTC_ARGCHK(out != NULL);
29 LTC_ARGCHK(outlen != NULL);
30
31 /* get the size */
32 if ((err = der_length_octet_string(inlen, &len)) != CRYPT_OK) {
33 return err;
34 }
35
36 /* too big? */
37 if (len > *outlen) {
38 *outlen = len;
39 return CRYPT_BUFFER_OVERFLOW;
40 }
41
42 /* encode the header+len */
43 x = 0;
44 out[x++] = 0x04;
45 len = *outlen - x;
46 if ((err = der_encode_asn1_length(inlen, out + x, &len)) != CRYPT_OK) {
47 return err;
48 }
49 x += len;
50
51 /* store octets */
52 for (y = 0; y < inlen; y++) {
53 out[x++] = in[y];
54 }
55
56 /* retun length */
57 *outlen = x;
58
59 return CRYPT_OK;
60 }
61
62 #endif
63