在JavaWeb項目中URL中字符串加密解密方案


URL由來:

一般來說,URL只能使用英文字母、阿拉伯數字和某些標點符號,不能使用其他文字和符號。比如,世界上有英文字母的網址 “http://www.abc.com”,但是沒有希臘字母的網址“http://www.aβγ.com”(讀作阿爾法-貝塔-伽瑪.com)。這是 因為網絡標准RFC 1738 做了硬性規定:

"...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL."

“只有字母和數字[0-9a-zA-Z]、一些特殊符號“$-_.+!*'(),”[不包括雙引號]、以及某些保留字,才可以不經過編碼直接用於 URL。”

這意味着,如果URL中有漢字,就必須編碼后使用。但是麻煩的是,RFC 1738沒有規定具體的編碼方法,而是交給應用程序(瀏覽器)自己決定。這導致“URL編碼”成為了一個混亂的領域。

URL加密的解決方案:

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;


public class UrlUtil {

    private static final String KEY = "myMw6qPt&3AD";
    private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtil.class);

    public static void main(String[] args) throws Exception {
        String source = "pwd=pwd";
        System.out.println("Excepted:" + source);

        String result = enCryptAndEncode(source);
        System.out.println("加密后:" + result);
        String source_2 = deCryptAndDecode(result);
        System.out.println("Actual:" + source_2);

        String isSuccess = source.equals(source_2) ? "Success" : "fail";
        System.out.println("Result:" + isSuccess);
    }


    public static String enCryptAndEncode(String content) {
        try {
            byte[] sourceBytes = enCryptAndEncode(content, KEY);
            return Base64.encodeBase64URLSafeString(sourceBytes);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return content;
        }
    }

    /**
     * 加密函數
     *
     * @param content 加密的內容
     * @param strKey  密鑰
     * @return 返回二進制字符數組
     * @throws Exception
     */
    public static byte[] enCryptAndEncode(String content, String strKey) throws Exception {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(strKey.getBytes()));

        SecretKey desKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, desKey);
        return cipher.doFinal(content.getBytes("UTF-8"));
    }

    public static String deCryptAndDecode(String content) throws Exception {
        byte[] targetBytes = Base64.decodeBase64(content);
        return deCryptAndDecode(targetBytes, KEY);
    }


    /**
     * 解密函數
     *
     * @param src    加密過的二進制字符數組
     * @param strKey 密鑰
     * @return
     * @throws Exception
     */
    public static String deCryptAndDecode(byte[] src, String strKey) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(strKey.getBytes()));

        SecretKey desKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, desKey);
        byte[] cByte = cipher.doFinal(src);
        return new String(cByte, "UTF-8");
    }


}

http://stackoverflow.com/questions/5217598/how-to-encrypt-and-decrypt-url-parameter-in-java

http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html#encodeBase64URLSafeString%28byte[]%29

一:前言
在軟件開發中,經常要對數據進行傳輸,數據在傳輸的過程中可能被攔截,被監聽,所以在傳輸數據的時候使用數據的原始內容進行傳輸的話,安全隱患是非常大的。因此就要對需要傳輸的數據進行在客戶端進行加密,然后在服務器進行解密!
加密和解密的算法有很多,主流有對稱加密和非對稱加密!兩者的區別就不在這里做介紹,有不懂的朋友可以去查Google。
(精讀閱讀本篇可能花費您10分鍾,略讀需5分鍾左右)

二:正文
1、這里就進行實戰的操作,從前台到后台,講解一個完整數據傳輸加密解密的流程。(很多的加密解密要么針對前端要么側重於后端)
前台JS中進行數據加密,通過發送數據到服務器,服務器進行解密!

2、首先拋出一個簡單的業務場景,在特定的業務場景中,使用特定的技術,解決特定的問題!
場景:系統中有一個登陸的功能,需要用戶輸入用戶名和密碼,用戶名和密碼需要在傳輸到服務器前進行加密,在服務器接收到數據后在進行解密!
注:只貼出關鍵部分的代碼,如需應用到你的系統中,只要理解關鍵代碼就ok了

(1):前台JSP和JS加密的內容

前台登錄部分采用的是一個form表單,表單內容在此省略。
下面主要介紹js部分代碼!首先在JSP中引入加密的js靜態件使用到的是crypto-js。

<script type="text/javascript" src="/xxx/dufy/common/js/core/aes.js"></script> <script type="text/javascript" src="/xxx/dufy/common/js/core/pad-zeropadding-min.js"></script>
//AES-128-CBC加密模式,key需要為16位,key和iv可以一樣 function encrypt(data) { var key = CryptoJS.enc.Latin1.parse('dufy20170329java'); var iv = CryptoJS.enc.Latin1.parse('dufy20170329java'); return CryptoJS.AES.encrypt(data, key, {iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding}).toString(); } //登錄 function login(){ var loginName = $("#loginName").val(); var loginPwd = $("#loginPwd").val(); //可能有驗證碼 captchadata captchakey 等數據,這里省略,只關注重點部分 loginName = encryptKuyu(loginName); loginPwd = encryptKuyu(loginPwd); var url = "${pageContext.request.contextPath}/customer/Login"; $.post(url,{"loginName":loginName,"pwd":loginPwd}, function(data){ if(result.success == "success"){ //登錄成功的操作 }else{ //登錄失敗的操作 } }); }

(2):后台JAVA代碼和解密工具類

//登錄的方法中接收到前台的參數,使用解密的方法進行解密! @RequestMapping(value = "/Login", method = RequestMethod.POST) @ResponseBody public String LoginKuyu(@RequestParam("loginName") String loginName, @RequestParam("pwd") String pwd, HttpServletRequest request, HttpServletResponse response) { try { // AES解碼用戶名和密碼 loginName = AesEncryptUtil.desEncrypt(loginName); pwd = AesEncryptUtil.desEncrypt(pwd); } catch (Exception e1) { loginName = ""; pwd = ""; //e1.printStackTrace(); log.error(e1); } loginName = loginName.trim(); pwd = pwd.trim(); //進行相應的登錄操作 }

解密的工具類:

/** * AES 128bit 加密解密工具類 * @author dufy */ import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AesEncryptUtil { //使用AES-128-CBC加密模式,key需要為16位,key和iv可以相同! private static String KEY = "dufy20170329java"; private static String IV = "dufy20170329java"; /** * 加密方法 * @param data 要加密的數據 * @param key 加密key * @param iv 加密iv * @return 加密的結果 * @throws Exception */ public static String encrypt(String data, String key, String iv) throws Exception { try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/補碼方式" int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return new Base64().encodeToString(encrypted); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 解密方法 * @param data 要解密的數據 * @param key 解密key * @param iv 解密iv * @return 解密的結果 * @throws Exception */ public static String desEncrypt(String data, String key, String iv) throws Exception { try { byte[] encrypted1 = new Base64().decode(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 使用默認的key和iv加密 * @param data * @return * @throws Exception */ public static String encrypt(String data) throws Exception { return encrypt(data, KEY, IV); } /** * 使用默認的key和iv解密 * @param data * @return * @throws Exception */ public static String desEncrypt(String data) throws Exception { return desEncrypt(data, KEY, IV); } /** * 測試 */ public static void main(String args[]) throws Exception { String test = "18729990110"; String data = null; String key = "dufy20170329java"; String iv = "dufy20170329java"; data = encrypt(test, key, iv); System.out.println(data); System.out.println(desEncrypt(data, key, iv)); } }

三:總結
1、整個流程我通過驗證,前台加密和后台可以正確解密!上面的關鍵代碼和文件我整理到github上,
地址:https://github.com/dufyun/kuyu/tree/master/aesUtilFile
2、學習知識和技術解決某些特定業務場景的的問題!
3、在互聯網中沒有什么是安全的,你認為的安全只是你認為的而已!
4、上面的這些只是一些拋磚的東西,很多東西可能不是很完善,但是整個從前台到后台的加密和解需要配合好,要不前台加密了,后台解密不了,這樣就不好了!

四:參考知識

https://cdnjs.com/libraries/crypto-js

http://jueyue.iteye.com/blog/1830792

在線AES加密解密地址:https://blog.zhengxianjun.com/online-tool/crypto/aes/

http://www.cnblogs.com/aflyun/p/6640492.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM