关于这个主题有很多问题,同样的解决方案,但这对我不起作用.我有一个加密的简单测试.加密/解密本身是有效的(只要我使用字节数组本身而不是字符串处理此测试).问题是不希望将它作为字节数组处理,而是作为String处理,但是当我将字节数组编码为字符串并返回时,生成的字节数组与原始字节数组不同,因此解密不再起作用.我在相应的字符串方法中尝试了以下参数:UTF-8,UTF8,UTF-16,UTF8.他们都没有工作.生成的字节数组与原始数组不同.任何想法为什么会这样?
加密:
public class NewEncrypter
{
private String algorithm = "DESede";
private Key key = null;
private Cipher cipher = null;
public NewEncrypter() throws NoSuchAlgorithmException, NoSuchPaddingException
{
key = KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance(algorithm);
}
public byte[] encrypt(String input) throws Exception
{
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes("UTF-16");
return cipher.doFinal(inputBytes);
}
public String decrypt(byte[] encryptionBytes) throws Exception
{
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
String recovered = new String(recoveredBytes, "UTF-16");
return recovered;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试的测试:
public class NewEncrypterTest
{
@Test
public …Run Code Online (Sandbox Code Playgroud) 使用String.getBytes()是否安全?当程序在具有不同默认值的不同系统上运行时会发生什么charset?我想我可以获得不同的内容byte[]?是否可以定义首选字符集Java 1.4?