项目中除了登陆,支付等接口采用rsa非对称加密,之外的采用aes对称加密,今天我们来认识一下aes加密。
什么是aes加密
高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。
生成一个密钥
/*
* 获得密钥key
*/
public static String getRawKey() {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 获取密匙生成器
kgen.init(128); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();// 生成密匙,可用多种方法来保存密匙
byte[] raw = skey.getEncoded();
return asHex(raw);
} catch (Exception e) {
return "";
}
}
加密
/**加密
*
* @param message 加密内容
* @param rawKey 密钥
* @return
*/
public static String getEncrypt(String message, String rawKey) {
byte[] key = asBin(rawKey);
try {
SecretKeySpec skeySpec = new SecretKeySpec(key,"AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes());
return asHex(encrypted);
} catch (Exception e) {
return "";
}
}
解密
/** 解密
*
* @param encrypted 解密内容
* @param rawKey 秘钥
* @return
*/
public static String getDecrypt(String encrypted, String rawKey) {
byte[] tmp = asBin(encrypted);
byte[] key = asBin(rawKey);
try{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(tmp);
return new String(decrypted);
} catch (Exception e) {
return "";
}
}
/*
* 转为十六进制
*/
private static String asHex(byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if ((buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString(buf[i] & 0xff, 16));
}
return strbuf.toString();
}
/*
* 转为二进制
*/
private static byte[] asBin(String src) {
if (src.length() < 1)
return null;
byte[] encrypted = new byte[src.length() / 2];
for (int i = 0; i < src.length() / 2; i++) {
int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);
encrypted[i] = (byte) (high * 16 + low);
}
return encrypted;
}
测试
List<Person> personList = new ArrayList<>();
int testMaxCount = 1000;//测试的最大数据条数
//添加测试数据
for (int i = 0; i < testMaxCount; i++) {
Person person = new Person();
person.setName(String.valueOf(i));
personList.add(person);
}
Gson gson = new Gson();
String jsonData = gson.toJson(personList).toString();
String key=AesUtil3.getRawKey();
Log.e(TAG, "aesTest3: key=" + key);
long start = System.currentTimeMillis();
String aesMiWen=AesUtil3.getEncrypt(jsonData,key);
long end = System.currentTimeMillis();
Log.e("MainActivity", "AES加密耗时 cost time---->" + (end - start));
Log.e(TAG, "aesTest3: 加密后--密文=" + aesMiWen);
start = System.currentTimeMillis();
String mingwen=AesUtil3.getDecrypt(aesMiWen,key);
end = System.currentTimeMillis();
Log.e("MainActivity", "AES解密耗时 cost time---->" + (end - start));
Log.e(TAG, "aesTest3: 解密后--明文=" + mingwen);
结果