版权声明:本文为博主原创文章,未经博主允许可以转载,但是得附上原文地址。 https://blog.csdn.net/fangqingyin/article/details/53535766
Android、Java都会使用到AES加密,方法很简单!
先导入包
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* 1.AES加密
* @param text: 需要加密的文本
* @param key: 加密key(匙)
*/
public static final String encrypt(@NonNull String text, @NonNull String key) {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(text.getBytes());
return byte2hex(encrypted).toLowerCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 2.AES解密
* @param pwd_txt: 需要解密的密文
* @param key: 加密的时候用到的key(匙)
*/
public static String Decrypt(@NonNull String pwd_txt, @NonNull String key) {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(pwd_txt);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* 16进制字符串转byte[]
* 用于解密
*/
public static byte[] hex2byte(@NonNull String strhex) {
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
}
return b;
}
/**
* byte[]转16進制字符串
* 用于加密
*/
public static String byte2hex(@NonNull byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}