Home | History | Annotate | Download | only in utf8
      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  * Tom St Denis, tomstdenis (at) gmail.com, http://libtomcrypt.com
     10  */
     11 #include "tomcrypt.h"
     12 
     13 /**
     14   @file der_length_utf8_string.c
     15   ASN.1 DER, get length of UTF8 STRING, Tom St Denis
     16 */
     17 
     18 #ifdef LTC_DER
     19 
     20 /** Return the size in bytes of a UTF-8 character
     21   @param c   The UTF-8 character to measure
     22   @return    The size in bytes
     23 */
     24 unsigned long der_utf8_charsize(const wchar_t c)
     25 {
     26    if (c <= 0x7F) {
     27       return 1;
     28    } else if (c <= 0x7FF) {
     29       return 2;
     30    } else if (c <= 0xFFFF) {
     31       return 3;
     32    } else {
     33       return 4;
     34    }
     35 }
     36 
     37 /**
     38   Gets length of DER encoding of UTF8 STRING
     39   @param in       The characters to measure the length of
     40   @param noctets  The number of octets in the string to encode
     41   @param outlen   [out] The length of the DER encoding for the given string
     42   @return CRYPT_OK if successful
     43 */
     44 int der_length_utf8_string(const wchar_t *in, unsigned long noctets, unsigned long *outlen)
     45 {
     46    unsigned long x, len;
     47 
     48    LTC_ARGCHK(in     != NULL);
     49    LTC_ARGCHK(outlen != NULL);
     50 
     51    len = 0;
     52    for (x = 0; x < noctets; x++) {
     53       if (in[x] < 0 || in[x] > 0x10FFFF) {
     54          return CRYPT_INVALID_ARG;
     55       }
     56       len += der_utf8_charsize(in[x]);
     57    }
     58 
     59    if (len < 128) {
     60       /* 0C LL DD DD DD ... */
     61       *outlen = 2 + len;
     62    } else if (len < 256) {
     63       /* 0C 81 LL DD DD DD ... */
     64       *outlen = 3 + len;
     65    } else if (len < 65536UL) {
     66       /* 0C 82 LL LL DD DD DD ... */
     67       *outlen = 4 + len;
     68    } else if (len < 16777216UL) {
     69       /* 0C 83 LL LL LL DD DD DD ... */
     70       *outlen = 5 + len;
     71    } else {
     72       return CRYPT_INVALID_ARG;
     73    }
     74 
     75    return CRYPT_OK;
     76 }
     77 
     78 #endif
     79 
     80 
     81 /* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/utf8/der_length_utf8_string.c,v $ */
     82 /* $Revision: 1.5 $ */
     83 /* $Date: 2006/12/16 17:41:21 $ */
     84