Util.java 19.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/* Util.java -- various utility routines.
   Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.

This file is a part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.  */


package gnu.java.security.util;

41 42
import gnu.java.lang.CPStringBuilder;

43 44 45
import java.math.BigInteger;

/**
46
 * A collection of utility methods used throughout this project.
47 48 49 50 51 52 53
 */
public class Util
{
  // Hex charset
  private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();

  // Base-64 charset
54 55
  private static final String BASE64_CHARS =
      "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./";
56 57 58 59 60 61 62 63 64 65

  private static final char[] BASE64_CHARSET = BASE64_CHARS.toCharArray();

  /** Trivial constructor to enforce Singleton pattern. */
  private Util()
  {
    super();
  }

  /**
66 67 68 69
   * Returns a string of hexadecimal digits from a byte array. Each byte is
   * converted to 2 hex symbols; zero(es) included.
   * <p>
   * This method calls the method with same name and three arguments as:
70
   * <pre>
71
   * toString(ba, 0, ba.length);
72
   * </pre>
73
   *
74
   * @param ba the byte array to convert.
75 76
   * @return a string of hexadecimal characters (two for each byte) representing
   *         the designated input byte array.
77 78 79 80 81 82 83
   */
  public static String toString(byte[] ba)
  {
    return toString(ba, 0, ba.length);
  }

  /**
84 85 86
   * Returns a string of hexadecimal digits from a byte array, starting at
   * <code>offset</code> and consisting of <code>length</code> bytes. Each
   * byte is converted to 2 hex symbols; zero(es) included.
87
   *
88 89
   * @param ba the byte array to convert.
   * @param offset the index from which to start considering the bytes to
90
   *          convert.
91
   * @param length the count of bytes, starting from the designated offset to
92 93 94
   *          convert.
   * @return a string of hexadecimal characters (two for each byte) representing
   *         the designated input byte sub-array.
95 96 97 98 99 100 101 102
   */
  public static final String toString(byte[] ba, int offset, int length)
  {
    char[] buf = new char[length * 2];
    for (int i = 0, j = 0, k; i < length;)
      {
        k = ba[offset + i++];
        buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
103
        buf[j++] = HEX_DIGITS[ k        & 0x0F];
104 105 106 107 108
      }
    return new String(buf);
  }

  /**
109 110 111 112 113
   * Returns a string of hexadecimal digits from a byte array. Each byte is
   * converted to 2 hex symbols; zero(es) included. The argument is treated as a
   * large little-endian integer and is returned as a large big-endian integer.
   * <p>
   * This method calls the method with same name and three arguments as:
114
   * <pre>
115
   * toReversedString(ba, 0, ba.length);
116
   * </pre>
117
   *
118
   * @param ba the byte array to convert.
119 120
   * @return a string of hexadecimal characters (two for each byte) representing
   *         the designated input byte array.
121 122 123 124 125 126 127
   */
  public static String toReversedString(byte[] ba)
  {
    return toReversedString(ba, 0, ba.length);
  }

  /**
128 129 130 131 132 133
   * Returns a string of hexadecimal digits from a byte array, starting at
   * <code>offset</code> and consisting of <code>length</code> bytes. Each
   * byte is converted to 2 hex symbols; zero(es) included.
   * <p>
   * The byte array is treated as a large little-endian integer, and is returned
   * as a large big-endian integer.
134
   *
135 136
   * @param ba the byte array to convert.
   * @param offset the index from which to start considering the bytes to
137
   *          convert.
138
   * @param length the count of bytes, starting from the designated offset to
139 140 141
   *          convert.
   * @return a string of hexadecimal characters (two for each byte) representing
   *         the designated input byte sub-array.
142 143 144 145 146 147 148 149
   */
  public static final String toReversedString(byte[] ba, int offset, int length)
  {
    char[] buf = new char[length * 2];
    for (int i = offset + length - 1, j = 0, k; i >= offset;)
      {
        k = ba[offset + i--];
        buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
150
        buf[j++] = HEX_DIGITS[ k        & 0x0F];
151 152 153 154 155
      }
    return new String(buf);
  }

  /**
156 157 158
   * <p>
   * Returns a byte array from a string of hexadecimal digits.
   * </p>
159
   *
160 161 162 163 164 165 166 167 168
   * @param s a string of hexadecimal ASCII characters
   * @return the decoded byte array from the input hexadecimal string.
   */
  public static byte[] toBytesFromString(String s)
  {
    int limit = s.length();
    byte[] result = new byte[((limit + 1) / 2)];
    int i = 0, j = 0;
    if ((limit % 2) == 1)
169
      result[j++] = (byte) fromDigit(s.charAt(i++));
170 171
    while (i < limit)
      {
172
        result[j  ] = (byte) (fromDigit(s.charAt(i++)) << 4);
173 174 175 176 177 178
        result[j++] |= (byte) fromDigit(s.charAt(i++));
      }
    return result;
  }

  /**
179 180 181
   * Returns a byte array from a string of hexadecimal digits, interpreting them
   * as a large big-endian integer and returning it as a large little-endian
   * integer.
182
   *
183 184 185 186 187 188 189 190 191
   * @param s a string of hexadecimal ASCII characters
   * @return the decoded byte array from the input hexadecimal string.
   */
  public static byte[] toReversedBytesFromString(String s)
  {
    int limit = s.length();
    byte[] result = new byte[((limit + 1) / 2)];
    int i = 0;
    if ((limit % 2) == 1)
192
      result[i++] = (byte) fromDigit(s.charAt(--limit));
193 194
    while (limit > 0)
      {
195
        result[i  ] = (byte) fromDigit(s.charAt(--limit));
196 197 198 199 200 201
        result[i++] |= (byte) (fromDigit(s.charAt(--limit)) << 4);
      }
    return result;
  }

  /**
202 203
   * Returns a number from <code>0</code> to <code>15</code> corresponding
   * to the designated hexadecimal digit.
204
   *
205 206 207 208 209
   * @param c a hexadecimal ASCII symbol.
   */
  public static int fromDigit(char c)
  {
    if (c >= '0' && c <= '9')
210
      return c - '0';
211
    else if (c >= 'A' && c <= 'F')
212
      return c - 'A' + 10;
213
    else if (c >= 'a' && c <= 'f')
214
      return c - 'a' + 10;
215 216 217 218 219
    else
      throw new IllegalArgumentException("Invalid hexadecimal digit: " + c);
  }

  /**
220 221
   * Returns a string of 8 hexadecimal digits (most significant digit first)
   * corresponding to the unsigned integer <code>n</code>.
222
   *
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
   * @param n the unsigned integer to convert.
   * @return a hexadecimal string 8-character long.
   */
  public static String toString(int n)
  {
    char[] buf = new char[8];
    for (int i = 7; i >= 0; i--)
      {
        buf[i] = HEX_DIGITS[n & 0x0F];
        n >>>= 4;
      }
    return new String(buf);
  }

  /**
238 239
   * Returns a string of hexadecimal digits from an integer array. Each int is
   * converted to 4 hex symbols.
240 241 242 243 244 245 246 247 248 249 250 251 252
   */
  public static String toString(int[] ia)
  {
    int length = ia.length;
    char[] buf = new char[length * 8];
    for (int i = 0, j = 0, k; i < length; i++)
      {
        k = ia[i];
        buf[j++] = HEX_DIGITS[(k >>> 28) & 0x0F];
        buf[j++] = HEX_DIGITS[(k >>> 24) & 0x0F];
        buf[j++] = HEX_DIGITS[(k >>> 20) & 0x0F];
        buf[j++] = HEX_DIGITS[(k >>> 16) & 0x0F];
        buf[j++] = HEX_DIGITS[(k >>> 12) & 0x0F];
253 254 255
        buf[j++] = HEX_DIGITS[(k >>>  8) & 0x0F];
        buf[j++] = HEX_DIGITS[(k >>>  4) & 0x0F];
        buf[j++] = HEX_DIGITS[ k         & 0x0F];
256 257 258 259 260
      }
    return new String(buf);
  }

  /**
261 262
   * Returns a string of 16 hexadecimal digits (most significant digit first)
   * corresponding to the unsigned long <code>n</code>.
263
   *
264 265 266 267 268 269 270 271
   * @param n the unsigned long to convert.
   * @return a hexadecimal string 16-character long.
   */
  public static String toString(long n)
  {
    char[] b = new char[16];
    for (int i = 15; i >= 0; i--)
      {
272
        b[i] = HEX_DIGITS[(int)(n & 0x0FL)];
273 274 275 276 277 278
        n >>>= 4;
      }
    return new String(b);
  }

  /**
279
   * Similar to the <code>toString()</code> method except that the Unicode
280 281
   * escape character is inserted before every pair of bytes. Useful to
   * externalise byte arrays that will be constructed later from such strings;
282
   * eg. s-box values.
283
   *
284 285 286 287 288 289 290 291
   * @throws ArrayIndexOutOfBoundsException if the length is odd.
   */
  public static String toUnicodeString(byte[] ba)
  {
    return toUnicodeString(ba, 0, ba.length);
  }

  /**
292
   * Similar to the <code>toString()</code> method except that the Unicode
293 294
   * escape character is inserted before every pair of bytes. Useful to
   * externalise byte arrays that will be constructed later from such strings;
295
   * eg. s-box values.
296
   *
297 298 299 300
   * @throws ArrayIndexOutOfBoundsException if the length is odd.
   */
  public static final String toUnicodeString(byte[] ba, int offset, int length)
  {
301
    CPStringBuilder sb = new CPStringBuilder();
302 303 304 305 306 307 308 309 310
    int i = 0;
    int j = 0;
    int k;
    sb.append('\n').append("\"");
    while (i < length)
      {
        sb.append("\\u");
        k = ba[offset + i++];
        sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
311
        sb.append(HEX_DIGITS[ k        & 0x0F]);
312 313
        k = ba[offset + i++];
        sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
314
        sb.append(HEX_DIGITS[ k        & 0x0F]);
315
        if ((++j % 8) == 0)
316
          sb.append("\"+").append('\n').append("\"");
317 318 319 320 321 322
      }
    sb.append("\"").append('\n');
    return sb.toString();
  }

  /**
323
   * Similar to the <code>toString()</code> method except that the Unicode
324 325
   * escape character is inserted before every pair of bytes. Useful to
   * externalise integer arrays that will be constructed later from such
326
   * strings; eg. s-box values.
327
   *
328 329
   * @throws ArrayIndexOutOfBoundsException if the length is not a multiple of
   *           4.
330 331 332
   */
  public static String toUnicodeString(int[] ia)
  {
333
    CPStringBuilder sb = new CPStringBuilder();
334 335 336 337 338 339 340 341 342 343 344 345 346 347
    int i = 0;
    int j = 0;
    int k;
    sb.append('\n').append("\"");
    while (i < ia.length)
      {
        k = ia[i++];
        sb.append("\\u");
        sb.append(HEX_DIGITS[(k >>> 28) & 0x0F]);
        sb.append(HEX_DIGITS[(k >>> 24) & 0x0F]);
        sb.append(HEX_DIGITS[(k >>> 20) & 0x0F]);
        sb.append(HEX_DIGITS[(k >>> 16) & 0x0F]);
        sb.append("\\u");
        sb.append(HEX_DIGITS[(k >>> 12) & 0x0F]);
348 349 350
        sb.append(HEX_DIGITS[(k >>>  8) & 0x0F]);
        sb.append(HEX_DIGITS[(k >>>  4) & 0x0F]);
        sb.append(HEX_DIGITS[ k         & 0x0F]);
351
        if ((++j % 4) == 0)
352
          sb.append("\"+").append('\n').append("\"");
353 354 355 356 357 358 359 360 361 362 363 364 365
      }
    sb.append("\"").append('\n');
    return sb.toString();
  }

  public static byte[] toBytesFromUnicode(String s)
  {
    int limit = s.length() * 2;
    byte[] result = new byte[limit];
    char c;
    for (int i = 0; i < limit; i++)
      {
        c = s.charAt(i >>> 1);
366
        result[i] = (byte)(((i & 1) == 0) ? c >>> 8 : c);
367 368 369 370 371
      }
    return result;
  }

  /**
372
   * Dumps a byte array as a string, in a format that is easy to read for
373
   * debugging. The string <code>m</code> is prepended to the start of each
374 375 376
   * line.
   * <p>
   * If <code>offset</code> and <code>length</code> are omitted, the whole
377
   * array is used. If <code>m</code> is omitted, nothing is prepended to each
378
   * line.
379
   *
380 381 382 383 384 385 386 387 388
   * @param data the byte array to be dumped.
   * @param offset the offset within <i>data</i> to start from.
   * @param length the number of bytes to dump.
   * @param m a string to be prepended to each line.
   * @return a string containing the result.
   */
  public static String dumpString(byte[] data, int offset, int length, String m)
  {
    if (data == null)
389
      return m + "null\n";
390
    CPStringBuilder sb = new CPStringBuilder(length * 3);
391
    if (length > 32)
392 393
      sb.append(m).append("Hexadecimal dump of ")
          .append(length).append(" bytes...\n");
394 395 396 397 398
    // each line will list 32 bytes in 4 groups of 8 each
    int end = offset + length;
    String s;
    int l = Integer.toString(length).length();
    if (l < 4)
399
      l = 4;
400 401 402 403 404 405 406 407 408
    for (; offset < end; offset += 32)
      {
        if (length > 32)
          {
            s = "         " + offset;
            sb.append(m).append(s.substring(s.length() - l)).append(": ");
          }
        int i = 0;
        for (; i < 32 && offset + i + 7 < end; i += 8)
409
          sb.append(toString(data, offset + i, 8)).append(' ');
410
        if (i < 32)
411 412
          for (; i < 32 && offset + i < end; i++)
            sb.append(byteToString(data[offset + i]));
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
        sb.append('\n');
      }
    return sb.toString();
  }

  public static String dumpString(byte[] data)
  {
    return (data == null) ? "null\n" : dumpString(data, 0, data.length, "");
  }

  public static String dumpString(byte[] data, String m)
  {
    return (data == null) ? "null\n" : dumpString(data, 0, data.length, m);
  }

  public static String dumpString(byte[] data, int offset, int length)
  {
    return dumpString(data, offset, length, "");
  }

  /**
434 435
   * Returns a string of 2 hexadecimal digits (most significant digit first)
   * corresponding to the lowest 8 bits of <code>n</code>.
436
   *
437 438 439 440 441 442 443 444 445 446
   * @param n the byte value to convert.
   * @return a string of 2 hex characters representing the input.
   */
  public static String byteToString(int n)
  {
    char[] buf = { HEX_DIGITS[(n >>> 4) & 0x0F], HEX_DIGITS[n & 0x0F] };
    return new String(buf);
  }

  /**
447
   * Converts a designated byte array to a Base-64 representation, with the
448
   * exceptions that (a) leading 0-byte(s) are ignored, and (b) the character
449 450 451
   * '.' (dot) shall be used instead of "+' (plus).
   * <p>
   * Used by SASL password file manipulation primitives.
452
   *
453 454
   * @param buffer an arbitrary sequence of bytes to represent in Base-64.
   * @return unpadded (without the '=' character(s)) Base-64 representation of
455
   *         the input.
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
   */
  public static final String toBase64(byte[] buffer)
  {
    int len = buffer.length, pos = len % 3;
    byte b0 = 0, b1 = 0, b2 = 0;
    switch (pos)
      {
      case 1:
        b2 = buffer[0];
        break;
      case 2:
        b1 = buffer[0];
        b2 = buffer[1];
        break;
      }
471
    CPStringBuilder sb = new CPStringBuilder();
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    int c;
    boolean notleading = false;
    do
      {
        c = (b0 & 0xFC) >>> 2;
        if (notleading || c != 0)
          {
            sb.append(BASE64_CHARSET[c]);
            notleading = true;
          }
        c = ((b0 & 0x03) << 4) | ((b1 & 0xF0) >>> 4);
        if (notleading || c != 0)
          {
            sb.append(BASE64_CHARSET[c]);
            notleading = true;
          }
        c = ((b1 & 0x0F) << 2) | ((b2 & 0xC0) >>> 6);
        if (notleading || c != 0)
          {
            sb.append(BASE64_CHARSET[c]);
            notleading = true;
          }
        c = b2 & 0x3F;
        if (notleading || c != 0)
          {
            sb.append(BASE64_CHARSET[c]);
            notleading = true;
          }
        if (pos >= len)
501
          break;
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
        else
          {
            try
              {
                b0 = buffer[pos++];
                b1 = buffer[pos++];
                b2 = buffer[pos++];
              }
            catch (ArrayIndexOutOfBoundsException x)
              {
                break;
              }
          }
      }
    while (true);

    if (notleading)
519
      return sb.toString();
520 521 522 523
    return "0";
  }

  /**
524 525 526 527
   * The inverse function of the above.
   * <p>
   * Converts a string representing the encoding of some bytes in Base-64 to
   * their original form.
528
   *
529 530
   * @param str the Base-64 encoded representation of some byte(s).
   * @return the bytes represented by the <code>str</code>.
531 532
   * @throws NumberFormatException if <code>str</code> is <code>null</code>,
   *           or <code>str</code> contains an illegal Base-64 character.
533 534 535 536 537 538
   * @see #toBase64(byte[])
   */
  public static final byte[] fromBase64(String str)
  {
    int len = str.length();
    if (len == 0)
539
      throw new NumberFormatException("Empty string");
540 541 542
    byte[] a = new byte[len + 1];
    int i, j;
    for (i = 0; i < len; i++)
543 544 545 546 547 548 549 550
      try
        {
          a[i] = (byte) BASE64_CHARS.indexOf(str.charAt(i));
        }
      catch (ArrayIndexOutOfBoundsException x)
        {
          throw new NumberFormatException("Illegal character at #" + i);
        }
551 552 553 554 555 556 557 558
    i = len - 1;
    j = len;
    try
      {
        while (true)
          {
            a[j] = a[i];
            if (--i < 0)
559
              break;
560 561
            a[j] |= (a[i] & 0x03) << 6;
            j--;
562
            a[j] = (byte)((a[i] & 0x3C) >>> 2);
563
            if (--i < 0)
564
              break;
565 566
            a[j] |= (a[i] & 0x0F) << 4;
            j--;
567
            a[j] = (byte)((a[i] & 0x30) >>> 4);
568
            if (--i < 0)
569
              break;
570 571 572 573
            a[j] |= (a[i] << 2);
            j--;
            a[j] = 0;
            if (--i < 0)
574
              break;
575 576 577 578 579 580 581 582
          }
      }
    catch (Exception ignored)
      {
      }
    try
      { // ignore leading 0-bytes
        while (a[j] == 0)
583
          j++;
584 585 586 587 588 589 590 591 592 593 594 595 596
      }
    catch (Exception x)
      {
        return new byte[1]; // one 0-byte
      }
    byte[] result = new byte[len - j + 1];
    System.arraycopy(a, j, result, 0, len - j + 1);
    return result;
  }

  // BigInteger utilities ----------------------------------------------------

  /**
597
   * Treats the input as the MSB representation of a number, and discards
598
   * leading zero elements. For efficiency, the input is simply returned if no
599
   * leading zeroes are found.
600
   *
601 602
   * @param n the {@link BigInteger} to trim.
   * @return the byte array representation of the designated {@link BigInteger}
603
   *         with no leading 0-bytes.
604 605 606 607 608
   */
  public static final byte[] trim(BigInteger n)
  {
    byte[] in = n.toByteArray();
    if (in.length == 0 || in[0] != 0)
609
      return in;
610 611 612
    int len = in.length;
    int i = 1;
    while (in[i] == 0 && i < len)
613
      ++i;
614 615 616 617 618 619
    byte[] result = new byte[len - i];
    System.arraycopy(in, i, result, 0, len - i);
    return result;
  }

  /**
620
   * Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}.
621
   *
622 623 624 625 626 627 628 629
   * @param x the {@link BigInteger} to display.
   * @return the string representation of the designated {@link BigInteger}.
   */
  public static final String dump(BigInteger x)
  {
    return dumpString(trim(x));
  }
}