【发布时间】:2021-04-05 13:09:59
【问题描述】:
我在 ECB 模式下将 AES 128 位加密升级到 AES 256 时遇到问题。但我无法找到任何解决方案。大多数解决方案都适用于 AES 256 CBC 模式。非常感谢任何帮助。
我得到的异常是由于填充错误
PS:我知道 AES 中 ECB 模式的漏洞,但这是我目前需要实现的。
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
public class Decrypt {
public static String decryptPayload(String payload) throws Exception {
byte[] keyBytes = {
0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x43, 0x53, 0x75, 0x63, 0x72, 0x65, 0x44, 0x4b, 0x55, 0x79
};
try {
payload = payload.replace(' ', '+');
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
final SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(
Base64.decodeBase64(payload)));
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return null;
}
}
我尝试的AES 256 ECB的实现如下:
public static String decrypt(String strToDecrypt, String secretKey) {
try
{
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
【问题讨论】:
-
您遇到了什么问题?
-
@njzk2 用我为 AES 256 ECB 尝试的实现更新了帖子
-
很好,但是实现的结果是什么?你有什么例外?
-
@njzk2 BadPaddingException 是我在使用 AES 256 ECB 解密时得到的
-
它是如何编码的/你如何确定编码是正确的?
标签: java cryptography aes