我在我的android应用程序中遇到了AES解密问题。我搜查了很多,但无法获得解决方案。AES解密:javax.crypto.BadPaddingException:在Android中损坏的垫块
这是步骤,我在做什么。
- 用我的密钥发送到Web服务器加密信用卡号码。
- Web服务器解密信用卡号并保存。
- 当我们从Web服务获取信用卡号码。
- 然后web服务器用相同的密钥加密信用卡号码并发送给我们。
- 现在,当我们解密这个数字时,它会抛出一些信用卡号码信息不好的填充异常。
加密信息与服务器的加密信息不一样,我们以加密格式发送。 尽管在iPhone应用程序中完成了相同的事情,并且iPhone能够成功解密信息。
我正在使用以下代码进行加密和解密。
public class AES256Cipher {
public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
public static String AES_Encode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return Base64.encodeToString(cipher.doFinal(textBytes), 0);
}
public static String AES_Decode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] textBytes =Base64.decode(str,0);
//byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(textBytes), "UTF-8");
}
请建议。
编辑: 我还有一件事,它是为< 16位数字信息工作。当我们放置16位数字信息时,它会抛出Exception解密。
请同时显示服务器端的代码。 – Codo
我不知道你的错误发生的原因,但是你的代码从加密的角度来看是不好的。 1)否IV 2)否MAC 3)直接使用文本作为密钥4)该代码根本不涉及密钥管理,这是实际的难题。 |您是否考虑过简单地使用TLS,而不是自己构建加密协议? |由于您使用的是信用卡,因此您需要查看PCI合规性。 – CodesInChaos
你的密钥有多久(以字节为单位)?初始化向量从哪里来?它如何与服务器端共享? – Codo