当前位置: 首页 > 工具软件 > Crypto-JS > 使用案例 >

crypto.js 前端加解密

南宫嘉
2023-12-01

简介
crypto-js是谷歌开发的一个纯JavaScript的加密算法类库,可以非常方便的在前端进行其所支持的加解密操作。目前crypto-js已支持的算法有:MD5、SHA-1、SHA-256、AES、RSA、Rabbit、MARC4、HMAC、HMAC-MD5、HMAC-SHA1、HMAC-SHA256、PBKDF2等。使用时可以引用总文件,也可以单独引用某一文件。
下载
https://github.com/brix/crypto-js/releases
使用
第一步
引入crypto-js.js文件

<script src="crypto-js.js"></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 );
}

第三步
后台接收处理解密

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类


```java
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页


```java

```css
<%@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>





 类似资料: