AES是android中一种常用的对称加密算法,通常用来传输一些私密的数据来与服务端的通信,加加密之前通常会对key或者要加密的值进行base64或者其他的方式包装,再进行加密,那解密时则需要先将包装还原再进行解密,今天记录一种常用的AES标准代码。
/**
* 加密
*/
public static String aesEncrypt(String encrypted, String keyWord) throws Exception {
String encryptStr = null;
try {
SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(encrypted.getBytes("utf-8"));
encryptStr = parseByte2HexStr(result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encryptStr;
}
/**
* 解密
*/
public static String AesDecrypt(String decrypted,String keyWord) throws Exception {
Key secretKey = new SecretKeySpec(keyWord.getBytes("utf-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, secretKey);
//执行操作
byte[] sb = HexString2Bytes(decrypted);
return new String(cipher.doFinal(sb));
}
/**
* 将二进制转换成16进制
*/
public static String parseByte2HexStr(final byte buf[]) {
StringBuffer sb = new StringBuffer();
for (byte element : buf) {
String hex = Integer.toHexString(element & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 从十六进制字符串到二进制字节数组转换
*/
public static byte[] HexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++) {
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b[i] = (byte) ((parse(c0) << 4) | parse(c1));
}
return b;
}