先看一个dmeo
public static void main(String[] args) {
String s1 = "hello world";
byte[] b = s1.getBytes(Charset.defaultCharset());
printByte(b);
String s2 = new String(b, Charset.defaultCharset());
System.out.println(s2);
printByte(s2.getBytes(Charset.defaultCharset()));
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
printByte(key);
String keyStr = new String(key, Charset.defaultCharset());
System.out.println(keyStr);
byte[] key2 = keyStr.getBytes(Charset.defaultCharset());
printByte(key2);
}
private static void printByte(byte[] bytes){
if(bytes!=null){
for (int i = 0; i < bytes.length; i++) {
System.out.print(bytes[i]+" ");
}
System.out.println();
}
}
运行结果
奇怪吗?为什么hello world可以准确的相互转换,而随机的byte数组再转回来时却变了。很多人都以为只要编码格式设置对了,转来转去应该不会有什么影响吧,其实不然。
通常我们有很多的场景需要以byte数组为参数进行传递,但是若是中间随意转换,再转回来时可能就发生了变化,比如加解密的场景,几乎底层所有的加解密都是byte[]为参数的。曾经有人写过这样的代码,找了很久没找到原因,因为大家都以为iv一开始就设置好了长度,encrypt里面肯定是16位的…
private static String test(String data){
String key = "";//从密钥管理处获取的密钥
//生成随机iv
byte[] iv = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
String ivStr = new String(iv, Charset.defaultCharset());
}
private static String encrypt(String key, String iv, String data){
byte[] ivBytes = iv.getBytes(Charset.defaultCharset());
if(ivBytes.length!=16){
return null;
}
return AESUtil.encrypt(data, key.getBytes(Charset.defaultCharset()), ivBytes);
}
这种场景其实也就初学者会这么写,通常加解密的工具,上层传递的参数确实都是字符串,但是这些字符串都是经过base64编码后的,不管是明文、密文、密钥还是向量盐值等都需要base64编码。经过base64编码后的密文、向量等甚至在网络传输中也不会失真。