byte[] 到 String returns 不同的 String

byte[] to String returns different String

对于给定的字节[],总是一样的,我想得到相应的字符串。 byte[] result 始终具有相同的值。

然而,返回的字符串永远不会相同,每次我启动我的应用程序时,结果都会改变。

byte[] results = cipher.doFinal(text.getBytes("UTF-8"));

String result = Base64.encodeBase64String(results);

我尝试了其他几种方法来获取我的字符串,例如 String result = new String(results, "UTF-8");Array,...但每次都不同。

这是在密码加密后发生的。这是完整的代码:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5padding");
byte[] keyBuf= new byte[16];

byte[] b= key.getBytes("UTF-8");
int len= b.length;
if (len > keyBuf.length) len = keyBuf.length;

System.arraycopy(b, 0, keyBuf, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBuf, "AES256");


byte[] ivBuf= new byte[16];
            //IvParameterSpec ivSpec = new IvParameterSpec(ivBuf);
IvParameterSpec ivSpec=null; 

cipher.init(Cipher.ENCRYPT_MODE, keySpec);

byte[] results = cipher.doFinal(text.getBytes("UTF-8"));

String result = Base64.encodeBase64String(results);
return result;

如何确保字符串 "result" 保持不变?

您每次加密时都使用不同的 IV - 因此每次加密时您也会得到不同的密文。您的 results 字节数组每次都不同,因此 base64 表示不同。

如果您真的想在每次加密相同的输入时都获得相同的结果,则每次都需要使用相同的 IV...但请注意,这会显着降低安全性。 (请注意,目前您甚至没有对 ivSpec 做任何事情。您可能希望将它作为第三个参数传递给 Cipher.init... IV,不只是使用 null.)