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
12 @file der_encode_utf8_string.c
13 ASN.1 DER, encode a UTF8 STRING, Tom St Denis
21 @param in The array of UTF8 to store (one per wchar_t)
22 @param inlen The number of UTF8 to store
23 @param out [out] The destination for the DER encoded UTF8 STRING
24 @param outlen [in/out] The max size and resulting size of the DER UTF8 STRING
25 @return CRYPT_OK if successful
27 int der_encode_utf8_string(const wchar_t *in, unsigned long inlen,
28 unsigned char *out, unsigned long *outlen)
30 unsigned long x, y, len;
32 LTC_ARGCHK(in != NULL);
33 LTC_ARGCHK(out != NULL);
34 LTC_ARGCHK(outlen != NULL);
37 for (x = len = 0; x < inlen; x++) {
38 if (!der_utf8_valid_char(in[x])) return CRYPT_INVALID_ARG;
39 len += der_utf8_charsize(in[x]);
44 } else if (len < 256) {
46 } else if (len < 65536UL) {
48 } else if (len < 16777216UL) {
51 return CRYPT_INVALID_ARG;
57 return CRYPT_BUFFER_OVERFLOW;
60 /* encode the header+len */
64 out[x++] = (unsigned char)len;
65 } else if (len < 256) {
67 out[x++] = (unsigned char)len;
68 } else if (len < 65536UL) {
70 out[x++] = (unsigned char)((len>>8)&255);
71 out[x++] = (unsigned char)(len&255);
72 } else if (len < 16777216UL) {
74 out[x++] = (unsigned char)((len>>16)&255);
75 out[x++] = (unsigned char)((len>>8)&255);
76 out[x++] = (unsigned char)(len&255);
78 /* coverity[dead_error_line] */
79 return CRYPT_INVALID_ARG;
83 for (y = 0; y < inlen; y++) {
84 switch (der_utf8_charsize(in[y])) {
85 case 1: out[x++] = (unsigned char)in[y]; break;
86 case 2: out[x++] = 0xC0 | ((in[y] >> 6) & 0x1F); out[x++] = 0x80 | (in[y] & 0x3F); break;
87 case 3: out[x++] = 0xE0 | ((in[y] >> 12) & 0x0F); out[x++] = 0x80 | ((in[y] >> 6) & 0x3F); out[x++] = 0x80 | (in[y] & 0x3F); break;
88 #if !defined(LTC_WCHAR_MAX) || LTC_WCHAR_MAX > 0xFFFF
89 case 4: out[x++] = 0xF0 | ((in[y] >> 18) & 0x07); out[x++] = 0x80 | ((in[y] >> 12) & 0x3F); out[x++] = 0x80 | ((in[y] >> 6) & 0x3F); out[x++] = 0x80 | (in[y] & 0x3F); break;
102 /* ref: $Format:%D$ */
103 /* git commit: $Format:%H$ */
104 /* commit time: $Format:%ai$ */