我有一个20字节的十六进制数组,它是SAH-1的输出[摘要]:
b1d5781111d84f7b3fe45a0852e59758cd7a87e5
如何将其作为16字节重用作为AES_CBC加密算法中的初始化IV:
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
Utils类:
public class Utils
{
private static String digits = "0123456789abcdef";
public static String toHex(byte[] data, int length)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i != length; i++)
{
int v = data[i] & 0xff;
buf.append(digits.charAt(v >> 4));
buf.append(digits.charAt(v & 0xf));
}
return buf.toString();
}
public static String toHex(byte[] data)
{
return toHex(data, data.length);
}
public static byte[] toByteArray(
String string)
{
byte[] bytes = new byte[string.length()];
char[] chars = string.toCharArray();
for (int i = 0; i != chars.length; i++)
{
bytes[i] = (byte)chars[i];
}
return bytes;
} }
答案 0 :(得分:0)
[编辑:更新了代码以使用注释中请求的代码]
使用Arrays.copyOf(keyBytes, 16)
:
MessageDigest hash = MessageDigest.getInstance("SHA1");
hash.update(Utils.toByteArray(input));
byte[] keyBytes = hash.digest();
keyBytes = Arrays.copyOf(keyBytes, 16); // use only first 128 bit
System.out.println("digest : " + Utils.toHex(keyBytes));