我尝试使用 key "01234567891234567890123456789012"
加密我的纯数据 "hello"
但问题是我的加密代码与 the online reference 不同。
这是我写的android代码:
String smykey = "01234567891234567890123456789012";
String hellos = "hello";
SecretKeySpec key = new SecretKeySpec(smykey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");//("AES/ECB/PKCS7Padding");//("ECB");//("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(hellos.getBytes());
代码生成,
android: 0x25 0x66...0x2d 0x87 (32 bytes)
ref: 0xa3 0xef...0x68 0x9f (16 bytes)
这段 Android 代码有什么问题?有人我感谢你的帮助吗?
最佳答案
在线引用做了一些不同的事情,Android 代码生成了正确的加密数据。
数据 hello
不是 block 大小(16 字节)的倍数,因此您必须指定填充 (PKCS#7)。
Android 使用 PKCS#7 填充,25669d21 dfd0fd6f cfef6cce 4ef12d87
是具有 256 位 key 、ECB 模式和 PKCS#7 填充的 AES 的正确结果。
smykey
和 hellos
使用 UTF-8 编码转换为数据。
使用 ECB 模式的情况很少见,它不安全,请使用带有随机 iv 的 CBC 模式(将 iv 添加到加密数据之前)。解密时不返回填充错误。
使用 HMAC 或更好的 key 扩展函数(如 PBKDF2)安全地将字符串密码除外到安全加密 key 。直接使用字符串作为 key 是不安全的。
关于java - AES 加密 256 ECB 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35786839/