標籤:for sub cas 傳輸 vax span ref dom aes
原文地址: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的倍數)。因此需要二進位的相互轉換
代碼如下:
Java代碼
- 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;
- }
-
-
-
- }
[轉]java利用AES實現URL的參數加密