AES有五种加密模式,有CBC、ECB、CTR、OCF、CFB五种
前言
? ? ? ? 正在做flutter版本的BLE项目的时候,发现flutter好多库不能实现Java 的这种 "AES/ECB/NoPadding" 方式的AES的加密,导致加密的报文和Java 的不一致,随机在网上找了好久终于找到了可以一个支持ECB 模式并且支持NoPadding填充模式的AES加密的库
一、Java版本对应的AES 加密
这个是java 版本的AES加密,基于ECB模式,并且使用了NoPadding方式填充。
public class AesUtil {
private static final String TAG = "AesUtil";
public static final byte[] key_oxo = 您的秘钥;
public static byte[] Encrypt(byte[] sSrc) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(key_oxo, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc);
return encrypted;
} catch (Exception ex) {
ex.printStackTrace();
Log.d(TAG, "ex: "+ex.getLocalizedMessage());
return null;
}
}
public static byte[] Decrypt(byte[] sSrc) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(key_oxo, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] dncrypted = cipher.doFinal(sSrc);
return dncrypted;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
二、Flutter版本的AES加密和解密
1.引入库
? 比较火的库,比如encrypt并不支持NoPadding填充方式,下面这个库可以支持,在pubspec.yaml中引入下面的库? 对应的地址?encryptions | Flutter Package
encryptions: ^1.1.0+1
??
2.封装成加解密工具
import 'dart:typed_data';
import 'package:encryptions/encryptions.dart';
import 'package:convert/convert.dart';
class AesUtil {
static List<int> key_oxo = 您的秘钥;
/**
* AES 加密
*/
static Future<String> encryptData(final String originHex) async {
Uint8List key = Uint8List.fromList(key_oxo);
Uint8List plain = Uint8List.fromList(hex.decode(originHex));
AES aes = AES.ofECB(key, PaddingScheme.NoPadding);
Uint8List encrypted = await aes.encrypt(plain);
String encryptHex = "";
for (int i = 0; i < encrypted.length; i++) {
String temp = encrypted[i].toRadixString(16);
if (temp.length == 1) {
temp = "0${temp}";
}
encryptHex = encryptHex + temp.toUpperCase();
}
return encryptHex;
}
/**
* AES 解密
*/
static Future<String> decryptData(final String originHex) async {
Uint8List key = Uint8List.fromList(key_oxo);
Uint8List plain = Uint8List.fromList(hex.decode(originHex));
AES aes = AES.ofECB(key, PaddingScheme.NoPadding);
Uint8List decrypted = await aes.decrypt(plain);
String decryptHex = "";
for (int i = 0; i < decrypted.length; i++) {
String temp = decrypted[i].toRadixString(16);
if (temp.length == 1) {
temp = "0${temp}";
}
decryptHex = decryptHex + temp.toUpperCase();
}
return decryptHex;
}
}
然后直接调用相应的方法就可以就行
String result1 = await AesUtil.encryptData(hex1);
print("hex1===${result1}");
String result2 = await AesUtil.decryptData(hex2);
print("hex2===${result2}");
总结
不同于的一般的项目使用CBC模式加密和解密使用,Iot设备一般常用基于ECB模式的通信加密方法。
|