]> pd.if.org Git - zpackage/blob - libtomcrypt/src/pk/asn1/der/utf8/der_length_utf8_string.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / pk / asn1 / der / utf8 / der_length_utf8_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_length_utf8_string.c
13   ASN.1 DER, get length of UTF8 STRING, Tom St Denis
14 */
15
16 #ifdef LTC_DER
17
18 /** Return the size in bytes of a UTF-8 character
19   @param c   The UTF-8 character to measure
20   @return    The size in bytes
21 */
22 unsigned long der_utf8_charsize(const wchar_t c)
23 {
24    if (c <= 0x7F) {
25       return 1;
26    } else if (c <= 0x7FF) {
27       return 2;
28 #if LTC_WCHAR_MAX == 0xFFFF
29    } else {
30       return 3;
31    }
32 #else
33    } else if (c <= 0xFFFF) {
34       return 3;
35    } else {
36       return 4;
37    }
38 #endif
39 }
40
41 /**
42   Test whether the given code point is valid character
43   @param c   The UTF-8 character to test
44   @return    1 - valid, 0 - invalid
45 */
46 int der_utf8_valid_char(const wchar_t c)
47 {
48    LTC_UNUSED_PARAM(c);
49 #if !defined(LTC_WCHAR_MAX) || LTC_WCHAR_MAX > 0xFFFF
50    if (c > 0x10FFFF) return 0;
51 #endif
52 #if LTC_WCHAR_MAX != 0xFFFF && LTC_WCHAR_MAX != 0xFFFFFFFF
53    if (c < 0) return 0;
54 #endif
55    return 1;
56 }
57
58 /**
59   Gets length of DER encoding of UTF8 STRING
60   @param in       The characters to measure the length of
61   @param noctets  The number of octets in the string to encode
62   @param outlen   [out] The length of the DER encoding for the given string
63   @return CRYPT_OK if successful
64 */
65 int der_length_utf8_string(const wchar_t *in, unsigned long noctets, unsigned long *outlen)
66 {
67    unsigned long x, len;
68
69    LTC_ARGCHK(in     != NULL);
70    LTC_ARGCHK(outlen != NULL);
71
72    len = 0;
73    for (x = 0; x < noctets; x++) {
74       if (!der_utf8_valid_char(in[x])) return CRYPT_INVALID_ARG;
75       len += der_utf8_charsize(in[x]);
76    }
77
78    if (len < 128) {
79       /* 0C LL DD DD DD ... */
80       *outlen = 2 + len;
81    } else if (len < 256) {
82       /* 0C 81 LL DD DD DD ... */
83       *outlen = 3 + len;
84    } else if (len < 65536UL) {
85       /* 0C 82 LL LL DD DD DD ... */
86       *outlen = 4 + len;
87    } else if (len < 16777216UL) {
88       /* 0C 83 LL LL LL DD DD DD ... */
89       *outlen = 5 + len;
90    } else {
91       return CRYPT_INVALID_ARG;
92    }
93
94    return CRYPT_OK;
95 }
96
97 #endif
98
99
100 /* ref:         $Format:%D$ */
101 /* git commit:  $Format:%H$ */
102 /* commit time: $Format:%ai$ */