AES加密 flutter java后台用的 AES/CBC/PKCS5Padding
可测试AES是否正确的网址
https://www.toolhelper.cn/SymmetricEncryption/AES
java后台代码如下
public static String encrypt(String clearText, String key, String iv) { byte[] result = null; try { byte[] key_bytes = toByte(MD5Util.getMD5String(MD5Util.getMD5String(key))); result = encrypt(clearText.getBytes(), key_bytes, iv); } catch (Exception e) { e.printStackTrace(); } return toHex(result); } private static byte[] encrypt(byte[] clear, byte[] raw, String iv) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv.getBytes())); byte[] encrypted = cipher.doFinal(clear); return encrypted; } public static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) { result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); } return result; } private static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); }
测试用例
clearText = test123456 key = 1691645969 iv = a0fe7c7c98e09e8c 最后aes后 30f3084aae678924002f6f0c41e77784
加密文本 test123456,java后台对 key时间戳 1691645969, MD5了两次,然后进行AES。AES的iv是 a0fe7c7c98e09e8c
切记 java 后台 AES/CBC/PKCS5Padding,PKCS5 和 PKCS7 是一样的。其他平台测试时可以用 PKCS7.
flutter 用的三方库
encrypt: ^5.0.1 #AES crypto: ^3.0.3 #MD5
导入头文件
import 'package:encrypt/encrypt.dart' as ce; import 'package:crypto/crypto.dart';
代码
DateTime today = DateTime.now(); int date1 = today.millisecondsSinceEpoch; print('当前时间戳:$date1'); var nonce = '$date1'; nonce = '1691645969'; print('nonce:$nonce'); var key = md5Crypto(md5Crypto(nonce)); print('key:$key'); var pwdCryptStr = aesEncrypted('test123456', key, 'a0fe7c7c98e09e8c'); print(pwdCryptStr);
开始 key 和 iv 都用的 fromUtf8,和后台生成的总是不一致,总以为是 mode 的问题。幸亏那测试网址了,可以一个个测试结果。
String aesEncrypted(String str, String aesKey, String ivStr){ final key = ce.Key.fromBase16(aesKey); final iv = ce.IV.fromUtf8(ivStr); final encrypter = ce.Encrypter(ce.AES(key, mode: ce.AESMode.cbc)); final encrypted = encrypter.encrypt(str,iv: iv); return encrypted.base16.toLowerCase(); }
在北京的灯中,有一盏是我家的。这个梦何时可以实现?哪怕微微亮。北京就像魔鬼训练营,有能力的留,没能力的走……