您的位置:首页 > 运维架构 > Tomcat

AES加密解密源码示例,以及解决:aes在tomcat解密中文乱码,在控制台解密中文不是乱码

2017-04-11 15:34 495 查看
这里使用AES128,进行加密,解密

加密示例:

/**
*
* 加密
*
* @param sSrc   原字符
* @param sKey   16位字符的key
* @return
* @throws Exception
* @return String
* @exception 异常描述
* @see
*/
public static String Encrypt128(String sSrc, String sKey) throws Exception {
if (sKey == null)
return null;
if (sKey.length() != 16)
throw new IllegalArgumentException("Key length must be 16.");
return doEncrypt(sSrc, sKey);
}

private static String doEncrypt(String sSrc, String sKey) throws Exception {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");//创建密码器
cipher.init(1, skeySpec);// 初始化
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));//加密

//字节转换成十六进制的字符串
return byte2hex(encrypted).toLowerCase();
}

/**
*
* 字节转换成十六进制的字符串
*
* @param b
* @return
* @return String
* @exception 异常描述
* @see
*/
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b
& 0xFF);
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}


解密示例:

/**
*
* 解密
*
* @param sSrc   原字符
* @param sKey   16位字符的key
* @return
* @throws Exception
* @return String
* @exception 异常描述
* @see
*/
public static String Decrypt128(String sSrc, String sKey) throws Exception {
if (sKey == null)
return null;
if (sKey.length() != 16)
throw new IllegalArgumentException("Key length must be 16.");
return doDecrypt(sSrc, sKey);
}

private static String doDecrypt(String sSrc, String sKey) throws Exception {
try {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(2, skeySpec);
byte[] encrypted1 = hex2byte(sSrc);

byte[] original = cipher.doFinal(encrypted1);
return new String(original,"utf-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

/**
*
* 十六进制的字符串转换成字节
*
* @param strhex
* @return
* @return byte[]
* @exception 异常描述
* @see
*/
public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
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;
}


如何解决:AES在tomcat解密中文乱码,在控制台解密中文不是乱码?

AES在解密后,用byte[]进行接收,需要使用new String();进行转换为字符。只需要指定new String()编码格式便可以解决解密时乱码问题。

即加密的时候:

byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));//加密

解密的时候:

byte[] original = cipher.doFinal(encrypted1);

return new String(original,"utf-8");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: