Matt said:
Is the best way to get the byte array out and then render it in hex or
similarly?
This works for me. It's reliable to and from the binary representation.
public static String hash (byte [] raw) throws Exception {
MessageDigest md = MessageDigest.getInstance ("MD5");
md.update(raw);
byte [] md5hash = md.digest();
BASE64Encoder encoder = new BASE64Encoder ();
Funnily enough I was just working on something similar just yesterday.
While this "isn't rocket science" it seems that it might come up often
enough that asking Sun to add it to the base API would be a good idea.
The basic problem is that the Arrays.toString( byte[] ) method isn't
flexible enough. The solution I came up with was to use String.format
to format each element. This allows some neat tricks with
Arrays.toSring(Object[]) as well.
To use this code, call toFormattedString() with the appropriate format
string.
ArrayUtils.toFormattedString( "%02X", bytes, null );
will give the result the OP is asking for, where "bytes" is an array of
bytes. Use "%02x" for lower case hex digits.
You can put hex digits into a string just like Arrays.toString() does:
ArrayUtils.toFormattedString( "%02X", bytes );
or you can have full control over the entire thing, specifying what to
use in place of the comma and brackets too.
ArrayUtils.toFormattedString( "%02X", bytes, "-", "(", ")" );
I'm in the process of turning this code into something resembling a
general purpose library, so things are kinda in flux. Let's see if I
can cut and paste this with out introducing syntax errors. I'm adding
support for a locale string and all other primitives, plus a proper
Javadoc. Ugh, the typing....
package local.utils;
public class ArrayUtils
{
private ArrayUtils()
{
}
public static String toFormattedString( byte[] bytes, String format )
{
return toFormattedString( bytes, format, ", ", "[", "]" );
}
public static String toFormattedString( String format, byte[] bytes,
String separator )
{
if( separator == null ) {
return toFormattedString( bytes, format, null, null, null );
}
else {
return toFormattedString( bytes, format, separator, "[", "]" );
}
}
public static String toFormattedString( byte[] bytes, String format,
String separator, String leader, String trailer )
{
int sepLen = separator != null ? separator.length() : 0;
// take a SWAG at the length for the StringBuilder
StringBuilder sb = new StringBuilder( bytes.length *
(format.length() +
sepLen) );
if( leader != null ) {
sb.append( leader );
}
if( separator != null ) {
for( int i = 0; i < bytes.length - 1; i++ ) {
sb.append( String.format( format, bytes
) );
sb.append( separator );
}
}
else {
for( int i = 0; i < bytes.length - 1; i++ ) {
sb.append( String.format( format, bytes ) );
}
}
sb.append( String.format( format, bytes[bytes.length - 1] ) );
if( trailer != null ) {
sb.append( trailer );
}
return sb.toString();
}
}