Debian Codegraph @

mcs/class/Novell.Directory.Ldap/Novell.Directory.Ldap.Utilclass/Base64.cs

raw
1 /******************************************************************************
2 * The MIT License
3 * Copyright (c) 2003 Novell Inc. www.novell.com
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the Software), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 *******************************************************************************/
23 //
24 // Novell.Directory.Ldap.Utilclass.Base64.cs
25 //
26 // Author:
27 // Sunil Kumar ([email protected])
28 //
29 // (C) 2003 Novell, Inc (http://www.novell.com)
30 //
31
32 using System;
33
34 namespace Novell.Directory.Ldap.Utilclass
35 {
36
37 /// <summary> The Base64 utility class performs base64 encoding and decoding.
38 ///
39 /// The Base64 Content-Transfer-Encoding is designed to represent
40 /// arbitrary sequences of octets in a form that need not be humanly
41 /// readable. The encoding and decoding algorithms are simple, but the
42 /// encoded data are consistently only about 33 percent larger than the
43 /// unencoded data. The base64 encoding algorithm is defined by
44 /// RFC 2045.
45 /// </summary>
46 public class Base64
47 {
48 /// <summary>Conversion table for encoding to base64.
49 ///
50 /// emap is a six-bit value to base64 (8-bit) converstion table.
51 /// For example, the value of the 6-bit value 15
52 /// is mapped to 0x50 which is the ASCII letter 'P', i.e. the letter P
53 /// is the base64 encoded character that represents the 6-bit value 15.
54 /// </summary>
55 /*
56 * 8-bit base64 encoded character base64 6-bit
57 * encoded original
58 * character binary value
59 */
60 private static readonly char[] emap = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; // 4-9, + /; 56-63
61
62 /// <summary>conversion table for decoding from base64.
63 ///
64 /// dmap is a base64 (8-bit) to six-bit value converstion table.
65 /// For example the ASCII character 'P' has a value of 80.
66 /// The value in the 80th position of the table is 0x0f or 15.
67 /// 15 is the original 6-bit value that the letter 'P' represents.
68 /// </summary>
69 /*
70 * 6-bit decoded value base64 base64
71 * encoded character
72 * value
73 *
74 * Note: about half of the values in the table are only place holders
75 */
76 private static readonly sbyte[] dmap = new sbyte[]{(sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x3e), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x3f), (sbyte) (0x34), (sbyte) (0x35), (sbyte) (0x36), (sbyte) (0x37), (sbyte) (0x38), (sbyte) (0x39), (sbyte) (0x3a), (sbyte) (0x3b), (sbyte) (0x3c), (sbyte) (0x3d), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x01), (sbyte) (0x02), (sbyte) (0x03), (sbyte) (0x04), (sbyte) (0x05), (sbyte) (0x06), (sbyte) (0x07), (sbyte) (0x08), (sbyte) (0x09), (sbyte) (0x0a), (sbyte) (0x0b), (sbyte) (0x0c), (sbyte) (0x0d), (sbyte) (0x0e), (sbyte) (0x0f), (sbyte) (0x10), (sbyte) (0x11), (sbyte) (0x12), (sbyte) (0x13), (sbyte) (0x14), (sbyte) (0x15), (sbyte) (0x16), (sbyte) (0x17), (sbyte) (0x18), (sbyte) (0x19), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x1a), (sbyte) (0x1b), (sbyte) (0x1c), (sbyte) (0x1d), (sbyte) (0x1e), (sbyte) (0x1f), (sbyte) (0x20), (sbyte) (0x21), (sbyte) (0x22), (sbyte) (0x23), (sbyte) (0x24), (sbyte) (0x25), (sbyte) (0x26), (sbyte) (0x27), (sbyte) (0x28), (sbyte) (0x29), (sbyte) (0x2a), (sbyte) (0x2b), (sbyte) (0x2c), (sbyte) (0x2d), (sbyte) (0x2e), (sbyte) (0x2f), (sbyte) (0x30), (sbyte) (0x31), (sbyte) (0x32), (sbyte) (0x33), (sbyte) (0x00), (
77 sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00), (sbyte) (0x00)}; // 120-127 'xyz '
78
79 /// <summary> Default constructor, don't allow instances of the
80 /// utility class to be created.
81 /// </summary>
82 private Base64()
83 {
84 return ;
85 }
86
87
88 /// <summary> Encodes the specified String into a base64 encoded String object.
89 ///
90 /// </summary>
91 /// <param name="inputString"> The String object to be encoded.
92 ///
93 /// </param>
94 /// <returns> a String containing the encoded value of the input.
95 /// </returns>
96 public static System.String encode(System.String inputString)
97 {
98 try
99 {
100 System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");
101 byte[] ibytes = encoder.GetBytes(inputString);
102 sbyte[] sbytes=SupportClass.ToSByteArray(ibytes);
103 return encode(sbytes);
104 }
105 catch (System.IO.IOException ue)
106 {
107 throw new System.SystemException("US-ASCII String encoding not supported by JVM");
108 }
109 }
110
111 /// <summary> Encodes the specified bytes into a base64 array of bytes.
112 /// Each byte in the return array represents a base64 character.
113 ///
114 /// </summary>
115 /// <param name="inputBytes"> the byte array to be encoded.
116 ///
117 /// </param>
118 /// <returns> a String containing the base64 encoded data
119 /// </returns>
120 [CLSCompliantAttribute(false)]
121 public static System.String encode(sbyte[] inputBytes)
122 {
123 int i, j, k;
124 int t, t1, t2;
125 int ntb; // number of three-bytes in inputBytes
126 bool onePadding = false, twoPaddings = false;
127 char[] encodedChars; // base64 encoded chars
128 int len = inputBytes.Length;
129
130 if (len == 0)
131 {
132 // No data, return no data.
133 return new System.Text.StringBuilder("").ToString();
134 }
135
136 // every three bytes will be encoded into four bytes
137 if (len % 3 == 0)
138 {
139 ntb = len / 3;
140 }
141 // the last one or two bytes will be encoded into
142 // four bytes with one or two paddings
143 else
144 {
145 ntb = len / 3 + 1;
146 }
147
148 // need two paddings
149 if ((len % 3) == 1)
150 {
151 twoPaddings = true;
152 }
153 // need one padding
154 else if ((len % 3) == 2)
155 {
156 onePadding = true;
157 }
158
159 encodedChars = new char[ntb * 4];
160
161 // map of decoded and encoded bits
162 // bits in 3 decoded bytes: 765432 107654 321076 543210
163 // bits in 4 encoded bytes: 76543210765432107654321076543210
164 // plain "AAA": 010000 010100 000101 000001
165 // base64 encoded "QUFB": 00010000000101000000010100000001
166 // one padding:
167 // bits in 2 decoded bytes: 765432 10 7654 3210
168 // bits in 4 encoded bytes: 765432107654 321076543210 '='
169 // plain "AA": 010000 010100 0001
170 // base64 encoded "QUE=": 00010000000101000000010000111101
171 // two paddings:
172 // bits in 1 decoded bytes: 765432 10
173 // bits in 4 encoded bytes: 7654321076543210 '=' '='
174 // plain "A": 010000 01
175 // base64 encoded "QQ==": 00010000000100000011110100111101
176 //
177 // note: the encoded bits which have no corresponding decoded bits
178 // are filled with zeros; '=' = 00111101.
179 for (i = 0, j = 0, k = 1; i < len; i += 3, j += 4, k++)
180 {
181
182 // build encodedChars[j]
183 t = 0x00ff & inputBytes[i];
184 encodedChars[j] = emap[t >> 2];
185
186 // build encodedChars[j+1]
187 if ((k == ntb) && twoPaddings)
188 {
189 encodedChars[j + 1] = emap[(t & 0x03) << 4];
190 encodedChars[j + 2] = '=';
191 encodedChars[j + 3] = '=';
192 break;
193 }
194 else
195 {
196 t1 = 0x00ff & inputBytes[i + 1];
197 encodedChars[j + 1] = emap[((t & 0x03) << 4) + ((t1 & 0xf0) >> 4)];
198 }
199
200 // build encodedChars[j+2]
201 if ((k == ntb) && onePadding)
202 {
203 encodedChars[j + 2] = emap[(t1 & 0x0f) << 2];
204 encodedChars[j + 3] = '=';
205 break;
206 }
207 else
208 {
209 t2 = 0x00ff & inputBytes[i + 2];
210 encodedChars[j + 2] = (emap[(t1 & 0x0f) << 2 | (t2 & 0xc0) >> 6]);
211 }
212
213 // build encodedChars[j+3]
214 encodedChars[j + 3] = (emap[(t2 & 0x3f)]);
215 }
216 return new System.String(encodedChars);
217 }
218
219
220 /// <summary> Decodes the input base64 encoded String.
221 /// The resulting binary data is returned as an array of bytes.
222 ///
223 /// </summary>
224 /// <param name="encodedString">The base64 encoded String object.
225 ///
226 /// </param>
227 /// <returns> The decoded byte array.
228 /// </returns>
229 [CLSCompliantAttribute(false)]
230 public static sbyte[] decode(System.String encodedString)
231 {
232 char[] c = new char[encodedString.Length];
233 SupportClass.GetCharsFromString(encodedString, 0, encodedString.Length, ref c, 0);
234 return decode(c);
235 }
236
237 /// <summary> Decodes the input base64 encoded array of characters.
238 /// The resulting binary data is returned as an array of bytes.
239 ///
240 /// </summary>
241 /// <param name="encodedChars">The character array containing the base64 encoded data.
242 ///
243 /// </param>
244 /// <returns> A byte array object containing decoded bytes.
245 /// </returns>
246 [CLSCompliantAttribute(false)]
247 public static sbyte[] decode(char[] encodedChars)
248 {
249 int i, j, k;
250 int ecLen = encodedChars.Length; // length of encodedChars
251 int gn = ecLen / 4; // number of four-byte groups in encodedChars
252 int dByteLen; // length of decoded bytes, default is '0'
253 bool onePad = false, twoPads = false;
254 sbyte[] decodedBytes; // decoded bytes
255
256 if (encodedChars.Length == 0)
257 {
258 return new sbyte[0];
259 }
260 // the number of encoded bytes should be multiple of 4
261 if ((ecLen % 4) != 0)
262 {
263 throw new System.SystemException("Novell.Directory.Ldap.ldif_dsml." + "Base64Decoder: decode: mal-formatted encode value");
264 }
265
266 // every four-bytes in encodedString, except the last one if it in the
267 // form of '**==' or '***=' ( can't be '*===' or '===='), will be
268 // decoded into three bytes.
269 if ((encodedChars[ecLen - 1] == (int) '=') && (encodedChars[ecLen - 2] == (int) '='))
270 {
271 // the last four bytes of encodedChars is in the form of '**=='
272 twoPads = true;
273 // the first two bytes of the last four-bytes of encodedChars will
274 // be decoded into one byte.
275 dByteLen = gn * 3 - 2;
276 decodedBytes = new sbyte[dByteLen];
277 }
278 else if (encodedChars[ecLen - 1] == '=')
279 {
280 // the last four bytes of encodedChars is in the form of '***='
281 onePad = true;
282 // the first two bytes of the last four-bytes of encodedChars will
283 // be decoded into two bytes.
284 dByteLen = gn * 3 - 1;
285 decodedBytes = new sbyte[dByteLen];
286 }
287 else
288 {
289 // the last four bytes of encodedChars is in the form of '****',
290 // e.g. no pad.
291 dByteLen = gn * 3;
292 decodedBytes = new sbyte[dByteLen];
293 }
294
295 // map of encoded and decoded bits
296 // no padding:
297 // bits in 4 encoded bytes: 76543210 76543210 76543210 76543210
298 // bits in 3 decoded bytes: 765432 107654 321076 543210
299 // base64 string "QUFB":00010000 00010100 000001010 0000001
300 // plain string "AAA": 010000 010100 000101 000001
301 // one padding:
302 // bits in 4 encoded bytes: 76543210 76543210 76543210 76543210
303 // bits in 2 decoded bytes: 765432 107654 3210
304 // base64 string "QUE=": 00010000 000101000 0000100 00111101
305 // plain string "AA": 010000 010100 0001
306 // two paddings:
307 // bits in 4 encoded bytes: 76543210 76543210 76543210 76543210
308 // bits in 1 decoded bytes: 765432 10
309 // base64 string "QQ==": 00010000 00010000 00111101 00111101
310 // plain string "A": 010000 01
311 for (i = 0, j = 0, k = 1; i < ecLen; i += 4, j += 3, k++)
312 {
313 // build decodedBytes[j].
314 decodedBytes[j] = (sbyte) (dmap[encodedChars[i]] << 2 | (dmap[encodedChars[i + 1]] & 0x30) >> 4);
315
316 // build decodedBytes[j+1]
317 if ((k == gn) && twoPads)
318 {
319 break;
320 }
321 else
322 {
323 decodedBytes[j + 1] = (sbyte) ((dmap[encodedChars[i + 1]] & 0x0f) << 4 | (dmap[encodedChars[i + 2]] & 0x3c) >> 2);
324 }
325
326 // build decodedBytes[j+2]
327 if ((k == gn) && onePad)
328 {
329 break;
330 }
331 else
332 {
333 decodedBytes[j + 2] = (sbyte) ((dmap[encodedChars[i + 2]] & 0x03) << 6 | dmap[encodedChars[i + 3]] & 0x3f);
334 }
335 }
336 return decodedBytes;
337 }
338
339 /// <summary> Decodes a base64 encoded StringBuffer.
340 /// Decodes all or part of the input base64 encoded StringBuffer, each
341 /// Character value representing a base64 character. The resulting
342 /// binary data is returned as an array of bytes.
343 ///
344 /// </summary>
345 /// <param name="encodedSBuf">The StringBuffer object that contains base64
346 /// encoded data.
347 /// </param>
348 /// <param name="start"> The start index of the base64 encoded data.
349 /// </param>
350 /// <param name="end"> The end index + 1 of the base64 encoded data.
351 ///
352 /// </param>
353 /// <returns> The decoded byte array
354 /// </returns>
355 [CLSCompliantAttribute(false)]
356 public static sbyte[] decode(System.Text.StringBuilder encodedSBuf, int start, int end)
357 {
358 int i, j, k;
359 int esbLen = end - start; // length of the encoded part
360 int gn = esbLen / 4; // number of four-bytes group in ebs
361 int dByteLen; // length of dbs, default is '0'
362 bool onePad = false, twoPads = false;
363 sbyte[] decodedBytes; // decoded bytes
364
365 if (encodedSBuf.Length == 0)
366 {
367 return new sbyte[0];
368 }
369 // the number of encoded bytes should be multiple of number 4
370 if ((esbLen % 4) != 0)
371 {
372 throw new System.SystemException("Novell.Directory.Ldap.ldif_dsml." + "Base64Decoder: decode error: mal-formatted encode value");
373 }
374
375 // every four-bytes in ebs, except the last one if it in the form of
376 // '**==' or '***=' ( can't be '*===' or '===='), will be decoded into
377 // three bytes.
378 if ((encodedSBuf[end - 1] == (int) '=') && (encodedSBuf[end - 2] == (int) '='))
379 {
380 // the last four bytes of ebs is in the form of '**=='
381 twoPads = true;
382 // the first two bytes of the last four-bytes of ebs will be
383 // decoded into one byte.
384 dByteLen = gn * 3 - 2;
385 decodedBytes = new sbyte[dByteLen];
386 }
387 else if (encodedSBuf[end - 1] == (int) '=')
388 {
389 // the last four bytes of ebs is in the form of '***='
390 onePad = true;
391 // the first two bytes of the last four-bytes of ebs will be
392 // decoded into two bytes.
393 dByteLen = gn * 3 - 1;
394 decodedBytes = new sbyte[dByteLen];
395 }
396 else
397 {
398 // the last four bytes of ebs is in the form of '****', eg. no pad.
399 dByteLen = gn * 3;
400 decodedBytes = new sbyte[dByteLen];
401 }
402
403 // map of encoded and decoded bits
404 // no padding:
405 // bits in 4 encoded bytes: 76543210 76543210 76543210 76543210
406 // bits in 3 decoded bytes: 765432 107654 321076 543210
407 // base64 string "QUFB":00010000 00010100 000001010 0000001
408 // plain string "AAA": 010000 010100 000101 000001
409 // one padding:
410 // bits in 4 encoded bytes: 76543210 76543210 76543210 76543210
411 // bits in 2 decoded bytes: 765432 107654 3210
412 // base64 string "QUE=": 00010000 000101000 0000100 00111101
413 // plain string "AA": 010000 010100 0001
414 // two paddings:
415 // bits in 4 encoded bytes: 76543210 76543210 76543210 76543210
416 // bits in 1 decoded bytes: 765432 10
417 // base64 string "QQ==": 00010000 00010000 00111101 00111101
418 // plain string "A": 010000 01
419 for (i = 0, j = 0, k = 1; i < esbLen; i += 4, j += 3, k++)
420 {
421 // build decodedBytes[j].
422 decodedBytes[j] = (sbyte) (dmap[encodedSBuf[start + i]] << 2 | (dmap[encodedSBuf[start + i + 1]] & 0x30) >> 4);
423
424 // build decodedBytes[j+1]
425 if ((k == gn) && twoPads)
426 {
427 break;
428 }
429 else
430 {
431 decodedBytes[j + 1] = (sbyte) ((dmap[encodedSBuf[start + i + 1]] & 0x0f) << 4 | (dmap[encodedSBuf[start + i + 2]] & 0x3c) >> 2);
432 }
433
434 // build decodedBytes[j+2]
435 if ((k == gn) && onePad)
436 {
437 break;
438 }
439 else
440 {
441 decodedBytes[j + 2] = (sbyte) ((dmap[encodedSBuf[start + i + 2]] & 0x03) << 6 | dmap[encodedSBuf[start + i + 3]] & 0x3f);
442 }
443 }
444 return decodedBytes;
445 }
446
447 /// <summary> Checks if the input byte array contains only safe values, that is,
448 /// the data does not need to be encoded for use with LDIF.
449 /// The rules for checking safety are based on the rules for LDIF
450 /// (Ldap Data Interchange Format) per RFC 2849. The data does
451 /// not need to be encoded if all the following are true:
452 ///
453 /// The data cannot start with the following byte values:
454 /// <pre>
455 /// 00 (NUL)
456 /// 10 (LF)
457 /// 13 (CR)
458 /// 32 (SPACE)
459 /// 58 (:)
460 /// 60 (LESSTHAN)
461 /// Any character with value greater than 127
462 /// (Negative for a byte value)
463 /// </pre>
464 /// The data cannot contain any of the following byte values:
465 /// <pre>
466 /// 00 (NUL)
467 /// 10 (LF)
468 /// 13 (CR)
469 /// Any character with value greater than 127
470 /// (Negative for a byte value)
471 /// </pre>
472 /// The data cannot end with a space.
473 ///
474 /// </summary>
475 /// <param name="bytes">the bytes to be checked.
476 ///
477 /// </param>
478 /// <returns> true if encoding not required for LDIF
479 /// </returns>
480 [CLSCompliantAttribute(false)]
481 public static bool isLDIFSafe(sbyte[] bytes)
482 {
483 int len = bytes.Length;
484 if (len > 0)
485 {
486 int testChar = bytes[0];
487 // unsafe if first character is a NON-SAFE-INIT-CHAR
488 if ((testChar == 0x00) || (testChar == 0x0A) || (testChar == 0x0D) || (testChar == 0x20) || (testChar == 0x3A) || (testChar == 0x3C) || (testChar < 0))
489 {
490 // non ascii (>127 is negative)
491 return false;
492 }
493 // unsafe if last character is a space
494 if (bytes[len - 1] == ' ')
495 {
496 return false;
497 }
498 // unsafe if contains any non safe character
499 if (len > 1)
500 {
501 for (int i = 1; i < bytes.Length; i++)
502 {
503 testChar = bytes[i];
504 if ((testChar == 0x00) || (testChar == 0x0A) || (testChar == 0x0D) || (testChar < 0))
505 {
506 // non ascii (>127 is negative)
507 return false;
508 }
509 }
510 }
511 }
512 return true;
513 }
514 /// <summary> Checks if the input String contains only safe values, that is,
515 /// the data does not need to be encoded for use with LDIF.
516 /// The rules for checking safety are based on the rules for LDIF
517 /// (Ldap Data Interchange Format) per RFC 2849. The data does
518 /// not need to be encoded if all the following are true:
519 ///
520 /// The data cannot start with the following char values:
521 /// <pre>
522 /// 00 (NUL)
523 /// 10 (LF)
524 /// 13 (CR)
525 /// 32 (SPACE)
526 /// 58 (:)
527 /// 60 (LESSTHAN)
528 /// Any character with value greater than 127
529 /// </pre>
530 /// The data cannot contain any of the following char values:
531 /// <pre>
532 /// 00 (NUL)
533 /// 10 (LF)
534 /// 13 (CR)
535 /// Any character with value greater than 127
536 /// </pre>
537 /// The data cannot end with a space.
538 ///
539 /// </summary>
540 /// <param name="str">the String to be checked.
541 ///
542 /// </param>
543 /// <returns> true if encoding not required for LDIF
544 /// </returns>
545 public static bool isLDIFSafe(System.String str)
546 {
547 try
548 {
549 System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");
550 byte[] ibytes = encoder.GetBytes(str);
551 sbyte[] sbytes=SupportClass.ToSByteArray(ibytes); return (isLDIFSafe(sbytes));
552 }
553 catch (System.IO.IOException ue)
554 {
555 throw new System.SystemException("UTF-8 String encoding not supported by JVM");
556 }
557 }
558
559 /* **************UTF-8 Validation methods and members*******************
560 * The following text is taken from draft-yergeau-rfc2279bis-02 and explains
561 * UTF-8 encoding:
562 *
563 *In UTF-8, characters are encoded using sequences of 1 to 6 octets.
564 * If the range of character numbers is restricted to U+0000..U+10FFFF
565 * (the UTF-16 accessible range), then only sequences of one to four
566 * octets will occur. The only octet of a "sequence" of one has the
567 * higher-order bit set to 0, the remaining 7 bits being used to encode
568 * the character number. In a sequence of n octets, n>1, the initial
569 * octet has the n higher-order bits set to 1, followed by a bit set to
570 * 0. The remaining bit(s) of that octet contain bits from the number
571 * of the character to be encoded. The following octet(s) all have the
572 * higher-order bit set to 1 and the following bit set to 0, leaving 6
573 * bits in each to contain bits from the character to be encoded.
574 *
575 * The table below summarizes the format of these different octet types.
576 * The letter x indicates bits available for encoding bits of the
577 * character number.
578 *
579 * <pre>
580 * Char. number range | UTF-8 octet sequence
581 * (hexadecimal) | (binary)
582 * --------------------+---------------------------------------------
583 * 0000 0000-0000 007F | 0xxxxxxx
584 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
585 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
586 * 0001 0000-001F FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
587 * 0020 0000-03FF FFFF | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
588 * 0400 0000-7FFF FFFF | 1111110x 10xxxxxx ... 10xxxxxx
589 * </pre>
590 */
591
592 /// <summary> Given the first byte in a sequence, getByteCount returns the number of
593 /// additional bytes in a UTF-8 character sequence (not including the first
594 /// byte).
595 ///
596 /// </summary>
597 /// <param name="b"> The first byte in a UTF-8 character sequence.
598 ///
599 /// </param>
600 /// <returns> the number of additional bytes in a UTF-8 character sequence.
601 /// </returns>
602 private static int getByteCount(sbyte b)
603 {
604 if (b > 0)
605 return 0;
606 if ((b & 0xE0) == 0xC0)
607 {
608 return 1; //one additional byte (2 bytes total)
609 }
610 if ((b & 0xF0) == 0xE0)
611 {
612 return 2; //two additional bytes (3 bytes total)
613 }
614 if ((b & 0xF8) == 0xF0)
615 {
616 return 3; //three additional bytes (4 bytes total)
617 }
618 if ((b & 0xFC) == 0xF8)
619 {
620 return 4; //four additional bytes (5 bytes total)
621 }
622 if ((b & 0xFF) == 0xFC)
623 {
624 return 5; //five additional bytes (6 bytes total)
625 }
626 return - 1;
627 }
628
629 /// <summary> Bit masks used to determine if a the value of UTF-8 byte sequence
630 /// is less than the minimum value.
631 ///
632 /// If the value of a byte sequence is less than the minimum value then
633 /// the number should be encoded in fewer bytes and is invalid. For example
634 /// If the first byte indicates that a sequence has three bytes in a
635 /// sequence. Then the top five bits cannot be zero. Notice the index into
636 /// the array is one less than the number of bytes in a sequence.
637 /// A validity test for this could be:
638 /// </summary>
639 private static readonly sbyte[][] lowerBoundMask = {new sbyte[]{0, 0}, new sbyte[]{(sbyte) (0x1E), (sbyte) (0x00)}, new sbyte[]{(sbyte) (0x0F), (sbyte) (0x20)}, new sbyte[]{(sbyte) (0x07), (sbyte) (0x30)}, new sbyte[]{(sbyte) (0x02), (sbyte) (0x38)}, new sbyte[]{(sbyte) (0x01), (sbyte) (0x3C)}};
640
641 /// <summary>mask to AND with a continuation byte: should equal continuationResult </summary>
642 private static sbyte continuationMask = (sbyte) SupportClass.Identity(0xC0);
643
644 /// <summary>expected result of ANDing a continuation byte with continuationMask </summary>
645 private static sbyte continuationResult = (sbyte) SupportClass.Identity(0x80);
646
647 /// <summary> Determines if an array of bytes contains only valid UTF-8 characters.
648 ///
649 /// UTF-8 is the standard encoding for Ldap strings. If a value contains
650 /// data that is not valid UTF-8 then data is lost converting the
651 /// value to a Java String.
652 ///
653 ///
654 /// In addition, Java Strings currently use UCS2 (Unicode Code Standard
655 /// 2-byte characters). UTF-8 can be encoded as USC2 and UCS4 (4-byte
656 /// characters). Some valid UTF-8 characters cannot be represented as UCS2
657 /// characters. To determine if all UTF-8 sequences can be encoded into
658 /// UCS2 characters (a Java String), specify the <code>isUCS2Only</code>
659 /// parameter as <code>true</code>.
660 ///
661 /// </summary>
662 /// <param name="array"> An array of bytes that are to be tested for valid UTF-8
663 /// encoding.
664 ///
665 /// </param>
666 /// <param name="isUCS2Only">true if the UTF-8 values must be restricted to fit
667 /// within UCS2 encoding (2 bytes)
668 /// </param>
669 /// <returns> true if all values in the byte array are valid UTF-8
670 /// sequences. If <code>isUCS2Only</code> is
671 /// <code>true</code>, the method returns false if a UTF-8
672 /// sequence generates any character that cannot be
673 /// represented as a UCS2 character (Java String)
674 /// </returns>
675 [CLSCompliantAttribute(false)]
676 public static bool isValidUTF8(sbyte[] array, bool isUCS2Only)
677 {
678 int index = 0;
679 while (index < array.Length)
680 {
681 int count = getByteCount(array[index]);
682 if (count == 0)
683 {
684 //anything that qualifies as count=0 is valid UTF-8
685 index++;
686 continue;
687 }
688
689 if (count == - 1 || index + count >= array.Length || (isUCS2Only && count >= 3))
690 {
691 /* Any count that puts us out of bounds for the index is
692 * invalid. Valid UCS2 characters can only have 2 additional
693 * bytes. (three total) */
694 return false;
695 }
696
697 /* Tests if the first and second byte are below the minimum bound */
698 if ((lowerBoundMask[count][0] & array[index]) == 0 && (lowerBoundMask[count][1] & array[index + 1]) == 0)
699 {
700 return false;
701 }
702
703 /* testing continuation on the second and following bytes */
704 for (int i = 1; i <= count; i++)
705 {
706 if ((array[index + i] & continuationMask) != continuationResult)
707 {
708 return false;
709 }
710 }
711 index += count + 1;
712 }
713 return true;
714 }
715 }
716 }