原文地址:http://h5566h.iteye.com/blog/1465426
很多时候需要在URL传参,希望URL参数能够加密,这里我结合了文章http://www.2cto.com/kf/201112/114046.html 提供的思路,然后结合java的ASE加密实现,写了下面的代码:
代码主要考虑两个问题:1、加密过的字符必须能有使用Url传输 2、加密算法必须是对称算法,通过私钥可以解密
另外:代码中为什么要把二进制转换成16进制呢,因为强制把byte数组转化成String的话,会出现乱码,第二是强制转换过的字符串,再转回byte数组的时候,二进制会变化,而且二进制的位数不是16的倍数(解密算法中的输入二进制数组的大小必须是16的倍数)。因此需要二进制的相互转换
代码如下:
- package p;
- import java.security.SecureRandom;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- public class AEStest {
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- String str = "user=admin&pwd=admin";
- String key = "12345678";
- String encrytStr;
- byte[] encrytByte;
- byte[] byteRe = enCrypt(str,key);
- //加密过的二进制数组转化成16进制的字符串
- encrytStr = parseByte2HexStr(byteRe);
- System.out.println("加密后:"+encrytStr);
- //加密过的16进制的字符串转化成二进制数组
- encrytByte = parseHexStr2Byte(encrytStr);
- System.out.println("解密后:"+deCrypt(encrytByte,key));
- }
- /**
- * 加密函数
- * @param content 加密的内容
- * @param strKey 密钥
- * @return 返回二进制字符数组
- * @throws Exception
- */
- public static byte[] enCrypt(String content,String strKey) throws Exception{
- KeyGenerator keygen;
- SecretKey desKey;
- Cipher c;
- byte[] cByte;
- String str = content;
- keygen = KeyGenerator.getInstance("AES");
- keygen.init(128, new SecureRandom(strKey.getBytes()));
- desKey = keygen.generateKey();
- c = Cipher.getInstance("AES");
- c.init(Cipher.ENCRYPT_MODE, desKey);
- cByte = c.doFinal(str.getBytes("UTF-8"));
- return cByte;
- }
- /** 解密函数
- * @param src 加密过的二进制字符数组
- * @param strKey 密钥
- * @return
- * @throws Exception
- */
- public static String deCrypt (byte[] src,String strKey) throws Exception{
- KeyGenerator keygen;
- SecretKey desKey;
- Cipher c;
- byte[] cByte;
- keygen = KeyGenerator.getInstance("AES");
- keygen.init(128, new SecureRandom(strKey.getBytes()));
- desKey = keygen.generateKey();
- c = Cipher.getInstance("AES");
- c.init(Cipher.DECRYPT_MODE, desKey);
- cByte = c.doFinal(src);
- return new String(cByte,"UTF-8");
- }
- /**2进制转化成16进制
- * @param buf
- * @return
- */
- public static String parseByte2HexStr(byte buf[]) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < buf.length; i++) {
- String hex = Integer.toHexString(buf[i] & 0xFF);
- if (hex.length() == 1) {
- hex = '0' + hex;
- }
- sb.append(hex.toUpperCase());
- }
- return sb.toString();
- }
- /**将16进制转换为二进制
- * @param hexStr
- * @return
- */
- public static byte[] parseHexStr2Byte(String hexStr) {
- if (hexStr.length() < 1)
- return null;
- byte[] result = new byte[hexStr.length()/2];
- for (int i = 0;i< hexStr.length()/2; i++) {
- int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
- int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
- result[i] = (byte) (high * 16 + low);
- }
- return result;
- }
- }