我已经实现了AES - Decryption方法,如下所示 - 这是完美的。 (我从其他程序收到加密文本)
public static String decrypt(String encryptedText, byte[] keyValue)
{
try
{
byte[] inputArr = Base64.getUrlDecoder().decode(encryptedText);
SecretKeySpec skSpec = new SecretKeySpec(keyValue, "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
int blockSize = cipher.getBlockSize();
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(inputArr, blockSize));
byte[] dataToDecrypt = Arrays.copyOfRange(inputArr, blockSize, inputArr.length);
cipher.init(Cipher.DECRYPT_MODE, skSpec, iv);
byte[] result = cipher.doFinal(dataToDecrypt);
return new String(result, StandardCharsets.UTF_8);
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
虽然我使用下面的代码加密文本(在发送到其他程序之前)没有产生预期的输出(如果我使用上面的解密程序来验证它只是返回null)
public static String encrypt(String strToEncrypt, String key)
{
try
{
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
int blockSize = cipher.getBlockSize();
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(strToEncrypt.getBytes(), blockSize));
byte[] dataToDecrypt = Arrays.copyOfRange(strToEncrypt.getBytes(), blockSize, strToEncrypt.getBytes().length);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(dataToDecrypt);
return Base64.getEncoder().encodeToString(encrypted);
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
我错过了什么吗?