jsp url傳參加密

package test;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class test02 {

public static void main(String[] args) throws Exception {  
    // TODO Auto-generated method stub  
    String str = "12";  
    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;   
}   

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章