SHA-256 returns 32 bytes by default (256 / 8 = 32
), not 16. The normal way to use a part of a hash is to use the first (leftmost) 16 bytes of the resulting hash. You can do this by applying the Java copyOf
method on the result of SHA-256.
Please use a real hexadecimal encoder to display the result (not to return a value, you don't need any String
instances at all). Using BigInteger
is error prone and may add or remove bytes.
Try for instance:
public static byte[] sha256digest16(String[] list) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
for(String s: list){
digest.update(s.getBytes("UTF-8"));
}
// so you have 32 bytes here
byte[] b = digest.digest();
// you can return it directly or you can cut it to 16 bytes
return Arrays.copyOf(b, 16);
}
For display as hexadecimals use:
public static String tohex(byte[] data) {
StringBuilder sb = new StringBuilder(data.length * 2);
for (int i = 0; i < data.length; i++) {
sb.append(String.format("%02X", data[i] & 0xFF));
}
return sb.toString();
}
Or use one of the hex encoders of the Apache commons codec, Bouncy Castle or Guava.