CryptoJS简单使用方法

CryptoJS下载链接:(1)想要下载别的版本:例如:4.1.1那就把后缀3.1.2改成4.1.1即可
https://registry.npmjs.org/crypto-js/-/crypto-js-3.1.2.tgz
https://registry.npmjs.org/crypto-js/-/crypto-js-4.1.1.tgz

使用
第一步
引入crypto-js.js文件

第二步
在提交前,对用户名和密码进行加密

function formencode(){

var KEY = CryptoJS.enc.Utf8.parse("1234567890123456");
var IV = CryptoJS.enc.Utf8.parse('1234567890123456');
var key = KEY;
var iv = IV;
var pwd = $("#password").val();

var pwdEncode = CryptoJS.enc.Utf8.parse(pwd);
var encryptedPassword = CryptoJS.AES.encrypt(pwdEncode, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
});
var encryptPasswordBase64 =  CryptoJS.enc.Base64.stringify(encryptedPassword.ciphertext);
$("#password").val(encryptPasswordBase64);        

var username = $("#username").val();
var nameuserEncode = CryptoJS.enc.Utf8.parse(username);
var encryptedUsername = CryptoJS.AES.encrypt(nameuserEncode, key, {
     iv: iv,
     mode: CryptoJS.mode.CBC,
     padding: CryptoJS.pad.ZeroPadding
});
var encryptedUsernameBase64 = CryptoJS.enc.Base64.stringify(encryptedUsername.ciphertext);
$("#username").val(encryptedUsernameBase64 );

}

第三步
后台接收处理解密

String username = h.get("username","");
String password = h.get("password","");
if(!username.equals("")) {

username = AesEncode.desEncrypt(username);
password = AesEncode.desEncrypt(password);
out.print("解密后的用户名/密码:" + username + "/" + password);

}

AesEncode类

package util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
 * @author 作者 :Mall
 */
public class AesEncode {

    // 使用AES-128-CBC加密模式,key需要为16位,key和iv可以相同!
    private static String KEY = "1234567890123456";

    private static String IV = "1234567890123456";

    /**
     * 加密方法
     * 
     * @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");// "算法/模式/补码方式"NoPadding
                                                                    // PkcsPadding
            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);
    }

}


实现的jsp页
<%@page import="util.AesEncode"%>
<%@page import="tea.entity.Http"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
Http h = new Http(request); 
String username = h.get("username","");
String password = h.get("password","");
if(!username.equals("")) {
    username = AesEncode.desEncrypt(username);
    password = AesEncode.desEncrypt(password);
    out.print("解密后的用户名/密码:" + username + "/" + password);
}
%>
<!doctype html>
<html>
<head>
    <script src="/tea/jquery-1.3.1.min.js"></script>
    <script src="crypto-js.js"></script>
</head>
<body>
    <form action="?">
        用户名:<input type="text" name="username" id="username"/>
        密     码:<input type="password" name="password" id="password"/>
        <input type="submit" value="提交"/><input type="button" onclick="formencode()" value="加密"/>
    </form>

</body>
</html>
<script>
function formencode(){
    var KEY = CryptoJS.enc.Utf8.parse("1234567890123456");
    var IV = CryptoJS.enc.Utf8.parse('1234567890123456');
    var key = KEY;
    var iv = IV;
    var pwd = $("#password").val();
    
    var pwdEncode = CryptoJS.enc.Utf8.parse(pwd);
    var encryptedPassword = CryptoJS.AES.encrypt(pwdEncode, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    });
    var encryptPasswordBase64 =  CryptoJS.enc.Base64.stringify(encryptedPassword.ciphertext);
    $("#password").val(encryptPasswordBase64);        
    
    var username = $("#username").val();
    var nameuserEncode = CryptoJS.enc.Utf8.parse(username);
    var encryptedUsername = CryptoJS.AES.encrypt(nameuserEncode, key, {
         iv: iv,
         mode: CryptoJS.mode.CBC,
         padding: CryptoJS.pad.ZeroPadding
    });
    var encryptedUsernameBase64 = CryptoJS.enc.Base64.stringify(encryptedUsername.ciphertext);
    $("#username").val(encryptedUsernameBase64 );
}
</script>

发表评论

电子邮件地址不会被公开。 必填项已用*标注