| 1 |
/* LibTomCrypt, modular cryptographic library -- Tom St Denis */ |
| 2 |
/* SPDX-License-Identifier: Unlicense */ |
| 3 |
#include "tomcrypt_private.h" |
| 4 |
|
| 5 |
/** |
| 6 |
@file der_encode_utf8_string.c |
| 7 |
ASN.1 DER, encode a UTF8 STRING, Tom St Denis |
| 8 |
*/ |
| 9 |
|
| 10 |
|
| 11 |
#ifdef LTC_DER |
| 12 |
|
| 13 |
/** |
| 14 |
Store an UTF8 STRING |
| 15 |
@param in The array of UTF8 to store (one per wchar_t) |
| 16 |
@param inlen The number of UTF8 to store |
| 17 |
@param out [out] The destination for the DER encoded UTF8 STRING |
| 18 |
@param outlen [in/out] The max size and resulting size of the DER UTF8 STRING |
| 19 |
@return CRYPT_OK if successful |
| 20 |
*/ |
| 21 |
int der_encode_utf8_string(const wchar_t *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 |
for (x = len = 0; x < inlen; x++) { |
| 33 |
if (!der_utf8_valid_char(in[x])) return CRYPT_INVALID_ARG; |
| 34 |
len += der_utf8_charsize(in[x]); |
| 35 |
} |
| 36 |
if ((err = der_length_asn1_length(len, &x)) != CRYPT_OK) { |
| 37 |
return err; |
| 38 |
} |
| 39 |
x += len + 1; |
| 40 |
|
| 41 |
/* too big? */ |
| 42 |
if (x > *outlen) { |
| 43 |
*outlen = x; |
| 44 |
return CRYPT_BUFFER_OVERFLOW; |
| 45 |
} |
| 46 |
|
| 47 |
/* encode the header+len */ |
| 48 |
x = 0; |
| 49 |
out[x++] = 0x0C; |
| 50 |
|
| 51 |
y = *outlen - x; |
| 52 |
if ((err = der_encode_asn1_length(len, out + x, &y)) != CRYPT_OK) { |
| 53 |
return err; |
| 54 |
} |
| 55 |
x += y; |
| 56 |
|
| 57 |
/* store UTF8 */ |
| 58 |
for (y = 0; y < inlen; y++) { |
| 59 |
switch (der_utf8_charsize(in[y])) { |
| 60 |
case 1: out[x++] = (unsigned char)in[y]; break; |
| 61 |
case 2: out[x++] = 0xC0 | ((in[y] >> 6) & 0x1F); out[x++] = 0x80 | (in[y] & 0x3F); break; |
| 62 |
case 3: out[x++] = 0xE0 | ((in[y] >> 12) & 0x0F); out[x++] = 0x80 | ((in[y] >> 6) & 0x3F); out[x++] = 0x80 | (in[y] & 0x3F); break; |
| 63 |
#if !defined(LTC_WCHAR_MAX) || LTC_WCHAR_MAX > 0xFFFF |
| 64 |
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; |
| 65 |
#endif |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
/* return length */ |
| 70 |
*outlen = x; |
| 71 |
|
| 72 |
return CRYPT_OK; |
| 73 |
} |
| 74 |
|
| 75 |
#endif |