1 /* Util.java -- various utility routines.
2 Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
4 This file is a part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or (at
9 your option) any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package gnu
.java
.security
.util
;
41 import java
.math
.BigInteger
;
44 * <p>A collection of utility methods used throughout this project.</p>
49 // Constants and variables
50 // -------------------------------------------------------------------------
53 private static final char[] HEX_DIGITS
= "0123456789ABCDEF".toCharArray();
56 private static final String BASE64_CHARS
= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./";
58 private static final char[] BASE64_CHARSET
= BASE64_CHARS
.toCharArray();
61 // -------------------------------------------------------------------------
63 /** Trivial constructor to enforce Singleton pattern. */
70 // -------------------------------------------------------------------------
73 * <p>Returns a string of hexadecimal digits from a byte array. Each byte is
74 * converted to 2 hex symbols; zero(es) included.</p>
76 * <p>This method calls the method with same name and three arguments as:</p>
79 * toString(ba, 0, ba.length);
82 * @param ba the byte array to convert.
83 * @return a string of hexadecimal characters (two for each byte)
84 * representing the designated input byte array.
86 public static String
toString(byte[] ba
)
88 return toString(ba
, 0, ba
.length
);
92 * <p>Returns a string of hexadecimal digits from a byte array, starting at
93 * <code>offset</code> and consisting of <code>length</code> bytes. Each byte
94 * is converted to 2 hex symbols; zero(es) included.</p>
96 * @param ba the byte array to convert.
97 * @param offset the index from which to start considering the bytes to
99 * @param length the count of bytes, starting from the designated offset to
101 * @return a string of hexadecimal characters (two for each byte)
102 * representing the designated input byte sub-array.
104 public static final String
toString(byte[] ba
, int offset
, int length
)
106 char[] buf
= new char[length
* 2];
107 for (int i
= 0, j
= 0, k
; i
< length
;)
109 k
= ba
[offset
+ i
++];
110 buf
[j
++] = HEX_DIGITS
[(k
>>> 4) & 0x0F];
111 buf
[j
++] = HEX_DIGITS
[k
& 0x0F];
113 return new String(buf
);
117 * <p>Returns a string of hexadecimal digits from a byte array. Each byte is
118 * converted to 2 hex symbols; zero(es) included. The argument is
119 * treated as a large little-endian integer and is returned as a
120 * large big-endian integer.</p>
122 * <p>This method calls the method with same name and three arguments as:</p>
125 * toReversedString(ba, 0, ba.length);
128 * @param ba the byte array to convert.
129 * @return a string of hexadecimal characters (two for each byte)
130 * representing the designated input byte array.
132 public static String
toReversedString(byte[] ba
)
134 return toReversedString(ba
, 0, ba
.length
);
138 * <p>Returns a string of hexadecimal digits from a byte array, starting at
139 * <code>offset</code> and consisting of <code>length</code> bytes. Each byte
140 * is converted to 2 hex symbols; zero(es) included.</p>
142 * <p>The byte array is treated as a large little-endian integer, and
143 * is returned as a large big-endian integer.</p>
145 * @param ba the byte array to convert.
146 * @param offset the index from which to start considering the bytes to
148 * @param length the count of bytes, starting from the designated offset to
150 * @return a string of hexadecimal characters (two for each byte)
151 * representing the designated input byte sub-array.
153 public static final String
toReversedString(byte[] ba
, int offset
, int length
)
155 char[] buf
= new char[length
* 2];
156 for (int i
= offset
+ length
- 1, j
= 0, k
; i
>= offset
;)
158 k
= ba
[offset
+ i
--];
159 buf
[j
++] = HEX_DIGITS
[(k
>>> 4) & 0x0F];
160 buf
[j
++] = HEX_DIGITS
[k
& 0x0F];
162 return new String(buf
);
166 * <p>Returns a byte array from a string of hexadecimal digits.</p>
168 * @param s a string of hexadecimal ASCII characters
169 * @return the decoded byte array from the input hexadecimal string.
171 public static byte[] toBytesFromString(String s
)
173 int limit
= s
.length();
174 byte[] result
= new byte[((limit
+ 1) / 2)];
176 if ((limit
% 2) == 1)
178 result
[j
++] = (byte) fromDigit(s
.charAt(i
++));
182 result
[j
] = (byte) (fromDigit(s
.charAt(i
++)) << 4);
183 result
[j
++] |= (byte) fromDigit(s
.charAt(i
++));
189 * <p>Returns a byte array from a string of hexadecimal digits, interpreting
190 * them as a large big-endian integer and returning it as a large
191 * little-endian integer.</p>
193 * @param s a string of hexadecimal ASCII characters
194 * @return the decoded byte array from the input hexadecimal string.
196 public static byte[] toReversedBytesFromString(String s
)
198 int limit
= s
.length();
199 byte[] result
= new byte[((limit
+ 1) / 2)];
201 if ((limit
% 2) == 1)
203 result
[i
++] = (byte) fromDigit(s
.charAt(--limit
));
207 result
[i
] = (byte) fromDigit(s
.charAt(--limit
));
208 result
[i
++] |= (byte) (fromDigit(s
.charAt(--limit
)) << 4);
214 * <p>Returns a number from <code>0</code> to <code>15</code> corresponding
215 * to the designated hexadecimal digit.</p>
217 * @param c a hexadecimal ASCII symbol.
219 public static int fromDigit(char c
)
221 if (c
>= '0' && c
<= '9')
225 else if (c
>= 'A' && c
<= 'F')
229 else if (c
>= 'a' && c
<= 'f')
234 throw new IllegalArgumentException("Invalid hexadecimal digit: " + c
);
238 * <p>Returns a string of 8 hexadecimal digits (most significant digit first)
239 * corresponding to the unsigned integer <code>n</code>.</p>
241 * @param n the unsigned integer to convert.
242 * @return a hexadecimal string 8-character long.
244 public static String
toString(int n
)
246 char[] buf
= new char[8];
247 for (int i
= 7; i
>= 0; i
--)
249 buf
[i
] = HEX_DIGITS
[n
& 0x0F];
252 return new String(buf
);
256 * <p>Returns a string of hexadecimal digits from an integer array. Each int
257 * is converted to 4 hex symbols.</p>
259 public static String
toString(int[] ia
)
261 int length
= ia
.length
;
262 char[] buf
= new char[length
* 8];
263 for (int i
= 0, j
= 0, k
; i
< length
; i
++)
266 buf
[j
++] = HEX_DIGITS
[(k
>>> 28) & 0x0F];
267 buf
[j
++] = HEX_DIGITS
[(k
>>> 24) & 0x0F];
268 buf
[j
++] = HEX_DIGITS
[(k
>>> 20) & 0x0F];
269 buf
[j
++] = HEX_DIGITS
[(k
>>> 16) & 0x0F];
270 buf
[j
++] = HEX_DIGITS
[(k
>>> 12) & 0x0F];
271 buf
[j
++] = HEX_DIGITS
[(k
>>> 8) & 0x0F];
272 buf
[j
++] = HEX_DIGITS
[(k
>>> 4) & 0x0F];
273 buf
[j
++] = HEX_DIGITS
[k
& 0x0F];
275 return new String(buf
);
279 * <p>Returns a string of 16 hexadecimal digits (most significant digit first)
280 * corresponding to the unsigned long <code>n</code>.</p>
282 * @param n the unsigned long to convert.
283 * @return a hexadecimal string 16-character long.
285 public static String
toString(long n
)
287 char[] b
= new char[16];
288 for (int i
= 15; i
>= 0; i
--)
290 b
[i
] = HEX_DIGITS
[(int) (n
& 0x0FL
)];
293 return new String(b
);
297 * <p>Similar to the <code>toString()</code> method except that the Unicode
298 * escape character is inserted before every pair of bytes. Useful to
299 * externalise byte arrays that will be constructed later from such strings;
300 * eg. s-box values.</p>
302 * @throws ArrayIndexOutOfBoundsException if the length is odd.
304 public static String
toUnicodeString(byte[] ba
)
306 return toUnicodeString(ba
, 0, ba
.length
);
310 * <p>Similar to the <code>toString()</code> method except that the Unicode
311 * escape character is inserted before every pair of bytes. Useful to
312 * externalise byte arrays that will be constructed later from such strings;
313 * eg. s-box values.</p>
315 * @throws ArrayIndexOutOfBoundsException if the length is odd.
317 public static final String
toUnicodeString(byte[] ba
, int offset
, int length
)
319 StringBuffer sb
= new StringBuffer();
323 sb
.append('\n').append("\"");
328 k
= ba
[offset
+ i
++];
329 sb
.append(HEX_DIGITS
[(k
>>> 4) & 0x0F]);
330 sb
.append(HEX_DIGITS
[k
& 0x0F]);
332 k
= ba
[offset
+ i
++];
333 sb
.append(HEX_DIGITS
[(k
>>> 4) & 0x0F]);
334 sb
.append(HEX_DIGITS
[k
& 0x0F]);
338 sb
.append("\"+").append('\n').append("\"");
341 sb
.append("\"").append('\n');
342 return sb
.toString();
346 * <p>Similar to the <code>toString()</code> method except that the Unicode
347 * escape character is inserted before every pair of bytes. Useful to
348 * externalise integer arrays that will be constructed later from such
349 * strings; eg. s-box values.</p>
351 * @throws ArrayIndexOutOfBoundsException if the length is not a multiple of 4.
353 public static String
toUnicodeString(int[] ia
)
355 StringBuffer sb
= new StringBuffer();
359 sb
.append('\n').append("\"");
360 while (i
< ia
.length
)
364 sb
.append(HEX_DIGITS
[(k
>>> 28) & 0x0F]);
365 sb
.append(HEX_DIGITS
[(k
>>> 24) & 0x0F]);
366 sb
.append(HEX_DIGITS
[(k
>>> 20) & 0x0F]);
367 sb
.append(HEX_DIGITS
[(k
>>> 16) & 0x0F]);
369 sb
.append(HEX_DIGITS
[(k
>>> 12) & 0x0F]);
370 sb
.append(HEX_DIGITS
[(k
>>> 8) & 0x0F]);
371 sb
.append(HEX_DIGITS
[(k
>>> 4) & 0x0F]);
372 sb
.append(HEX_DIGITS
[k
& 0x0F]);
376 sb
.append("\"+").append('\n').append("\"");
379 sb
.append("\"").append('\n');
380 return sb
.toString();
383 public static byte[] toBytesFromUnicode(String s
)
385 int limit
= s
.length() * 2;
386 byte[] result
= new byte[limit
];
388 for (int i
= 0; i
< limit
; i
++)
390 c
= s
.charAt(i
>>> 1);
391 result
[i
] = (byte) (((i
& 1) == 0) ? c
>>> 8 : c
);
397 * <p>Dumps a byte array as a string, in a format that is easy to read for
398 * debugging. The string <code>m</code> is prepended to the start of each
401 * <p>If <code>offset</code> and <code>length</code> are omitted, the whole
402 * array is used. If <code>m</code> is omitted, nothing is prepended to each
405 * @param data the byte array to be dumped.
406 * @param offset the offset within <i>data</i> to start from.
407 * @param length the number of bytes to dump.
408 * @param m a string to be prepended to each line.
409 * @return a string containing the result.
411 public static String
dumpString(byte[] data
, int offset
, int length
, String m
)
417 StringBuffer sb
= new StringBuffer(length
* 3);
420 sb
.append(m
).append("Hexadecimal dump of ").append(length
).append(
423 // each line will list 32 bytes in 4 groups of 8 each
424 int end
= offset
+ length
;
426 int l
= Integer
.toString(length
).length();
431 for (; offset
< end
; offset
+= 32)
436 sb
.append(m
).append(s
.substring(s
.length() - l
)).append(": ");
439 for (; i
< 32 && offset
+ i
+ 7 < end
; i
+= 8)
441 sb
.append(toString(data
, offset
+ i
, 8)).append(' ');
445 for (; i
< 32 && offset
+ i
< end
; i
++)
447 sb
.append(byteToString(data
[offset
+ i
]));
452 return sb
.toString();
455 public static String
dumpString(byte[] data
)
457 return (data
== null) ?
"null\n" : dumpString(data
, 0, data
.length
, "");
460 public static String
dumpString(byte[] data
, String m
)
462 return (data
== null) ?
"null\n" : dumpString(data
, 0, data
.length
, m
);
465 public static String
dumpString(byte[] data
, int offset
, int length
)
467 return dumpString(data
, offset
, length
, "");
471 * <p>Returns a string of 2 hexadecimal digits (most significant digit first)
472 * corresponding to the lowest 8 bits of <code>n</code>.</p>
474 * @param n the byte value to convert.
475 * @return a string of 2 hex characters representing the input.
477 public static String
byteToString(int n
)
479 char[] buf
= { HEX_DIGITS
[(n
>>> 4) & 0x0F], HEX_DIGITS
[n
& 0x0F] };
480 return new String(buf
);
484 * <p>Converts a designated byte array to a Base-64 representation, with the
485 * exceptions that (a) leading 0-byte(s) are ignored, and (b) the character
486 * '.' (dot) shall be used instead of "+' (plus).</p>
488 * <p>Used by SASL password file manipulation primitives.</p>
490 * @param buffer an arbitrary sequence of bytes to represent in Base-64.
491 * @return unpadded (without the '=' character(s)) Base-64 representation of
494 public static final String
toBase64(byte[] buffer
)
496 int len
= buffer
.length
, pos
= len
% 3;
497 byte b0
= 0, b1
= 0, b2
= 0;
508 StringBuffer sb
= new StringBuffer();
510 boolean notleading
= false;
513 c
= (b0
& 0xFC) >>> 2;
514 if (notleading
|| c
!= 0)
516 sb
.append(BASE64_CHARSET
[c
]);
519 c
= ((b0
& 0x03) << 4) | ((b1
& 0xF0) >>> 4);
520 if (notleading
|| c
!= 0)
522 sb
.append(BASE64_CHARSET
[c
]);
525 c
= ((b1
& 0x0F) << 2) | ((b2
& 0xC0) >>> 6);
526 if (notleading
|| c
!= 0)
528 sb
.append(BASE64_CHARSET
[c
]);
532 if (notleading
|| c
!= 0)
534 sb
.append(BASE64_CHARSET
[c
]);
549 catch (ArrayIndexOutOfBoundsException x
)
559 return sb
.toString();
565 * <p>The inverse function of the above.</p>
567 * <p>Converts a string representing the encoding of some bytes in Base-64
568 * to their original form.</p>
570 * @param str the Base-64 encoded representation of some byte(s).
571 * @return the bytes represented by the <code>str</code>.
572 * @throws NumberFormatException if <code>str</code> is <code>null</code>, or
573 * <code>str</code> contains an illegal Base-64 character.
574 * @see #toBase64(byte[])
576 public static final byte[] fromBase64(String str
)
578 int len
= str
.length();
581 throw new NumberFormatException("Empty string");
583 byte[] a
= new byte[len
+ 1];
585 for (i
= 0; i
< len
; i
++)
589 a
[i
] = (byte) BASE64_CHARS
.indexOf(str
.charAt(i
));
591 catch (ArrayIndexOutOfBoundsException x
)
593 throw new NumberFormatException("Illegal character at #" + i
);
607 a
[j
] |= (a
[i
] & 0x03) << 6;
609 a
[j
] = (byte) ((a
[i
] & 0x3C) >>> 2);
614 a
[j
] |= (a
[i
] & 0x0F) << 4;
616 a
[j
] = (byte) ((a
[i
] & 0x30) >>> 4);
630 catch (Exception ignored
)
635 { // ignore leading 0-bytes
643 return new byte[1]; // one 0-byte
645 byte[] result
= new byte[len
- j
+ 1];
646 System
.arraycopy(a
, j
, result
, 0, len
- j
+ 1);
650 // BigInteger utilities ----------------------------------------------------
653 * <p>Treats the input as the MSB representation of a number, and discards
654 * leading zero elements. For efficiency, the input is simply returned if no
655 * leading zeroes are found.</p>
657 * @param n the {@link BigInteger} to trim.
658 * @return the byte array representation of the designated {@link BigInteger}
659 * with no leading 0-bytes.
661 public static final byte[] trim(BigInteger n
)
663 byte[] in
= n
.toByteArray();
664 if (in
.length
== 0 || in
[0] != 0)
670 while (in
[i
] == 0 && i
< len
)
674 byte[] result
= new byte[len
- i
];
675 System
.arraycopy(in
, i
, result
, 0, len
- i
);
680 * <p>Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}.
683 * @param x the {@link BigInteger} to display.
684 * @return the string representation of the designated {@link BigInteger}.
686 public static final String
dump(BigInteger x
)
688 return dumpString(trim(x
));