前端(cryptoJS)加解密并与后端加解密保持一致(DES的CBC模式)

该博客展示了如何在前端使用cryptoJS库进行DES加密,并在后端使用Java进行解密,确保数据在传输过程中的安全性。通过示例代码,详细解释了加密和解密的过程,以及关键参数如密钥和初始化向量的设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.前端使用cryptoJS

<!-- <%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
request.getSession().setAttribute("ContextPath",basePath);

%>-->

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <base href="<%=basePath%>">

        <title>My JSP 'index.jsp' starting page</title>
    </head>
    <script type="text/javascript" src="./cryptoJS/rollups/tripledes.js" charset="UTF-8"></script>
    <script type="text/javascript" src="./cryptoJS/components/mode-ecb.js" charset="UTF-8"></script>
    <body>
        This is my JSP page.
        <button onclick="init()">计算</button>
        <br>
    </body>
    <script type="text/javascript">
        function init(){
			var a = encrypValue("noon");
			alert(a);
			var b = decrypValue(a);
			alert(b);
        }
		//解密
		function decrypValue (value) {
			var keyHex = CryptoJS.enc.Base64.parse("Txs5R1lhID8=");
			var ivHex = CryptoJS.enc.Base64.parse("GBsfNUJhISo=");
			var decrypted = CryptoJS.DES.decrypt({
				ciphertext: CryptoJS.enc.Base64.parse(value)
			}, keyHex, {
				iv:ivHex,
				mode: CryptoJS.mode.CBC,
				padding:CryptoJS.pad.Pkcs7
			});
			return decrypted.toString(CryptoJS.enc.Utf8);
		};
		//加密
		function encrypValue (value) {
			var keyHex = CryptoJS.enc.Base64.parse("Txs5R1lhID8=");
			var ivHex = CryptoJS.enc.Base64.parse("GBsfNUJhISo=");
			var encrypted = CryptoJS.DES.encrypt(value, keyHex, {
				iv:ivHex,
				mode: CryptoJS.mode.CBC,
				padding:CryptoJS.pad.Pkcs7
			});
			return encrypted.toString();
		}
		
    </script>
</html>

2.后端java

package cc.com;

import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Base64;


/**
 * DES对称加密算法
 * @see 
 */
public class Test2 {

    public static final String KEY_ALGORITHM = "DES";
    public static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
/*    private static final byte[] rgbKey = { 79, 27, 57, 71, 89, 97, 32, 63 };
    private static final byte[] rgbIV = { 24, 27, 31, 53, 66, 97, 33, 42 };*/
    private static final String keyHex = "Txs5R1lhID8=";
    private static final String ivHex = "GBsfNUJhISo=";


    /**
     * 生成密钥
     * @param seed 密钥
     * @return 字符串
     * @throws Exception 异常
     */
    public static String initkey() throws Exception {
        return initkey(null);
    }

    /**
     * 生成密钥
     * @param seed 密钥
     * @return 字符串
     * @throws Exception 异常
     */
    public static String initkey(String seed) throws Exception {
        SecureRandom secureRandom = null;

        if(seed != null){
            secureRandom = new SecureRandom(Base64.decodeBase64(seed));
        }else{
            secureRandom = new SecureRandom();
        }

        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        kg.init(secureRandom);
        SecretKey secretKey = kg.generateKey();

        return Base64.encodeBase64String(secretKey.getEncoded());
    }

//  /**
//   * 转换密钥
//   */
//  private static Key toKey(byte[] key) throws Exception {
//      DESedeKeySpec dks = new DESedeKeySpec(key);
//      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
//      SecretKey secretKey = keyFactory.generateSecret(dks);
//      return secretKey;

//  }
    /**
     * 转换密钥
     */
    private static SecretKey toKey(byte[] key) throws Exception {
        DESKeySpec keySpec = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密数据
     * @param data 待加密数据
     * @param key  密钥
     * @return 加密后的数据
     */
    public static String encrypt(String data) throws Exception {
        Key k = toKey(Base64.decodeBase64(keyHex));
        AlgorithmParameterSpec iv = new IvParameterSpec(Base64.decodeBase64(ivHex));
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, k,iv);
        /*byte[] encryptData = cipher.doFinal(data.getBytes());
        return Base64.encodeBase64String(encryptData);*/
        byte[] encryptData = cipher.doFinal(data.getBytes("utf-8"));
        return Base64.encodeBase64URLSafeString(encryptData);
    }

    /**
     * 解密数据
     * @param data 待解密数据
     * @param key  密钥
     * @return 解密后的数据
     */
    public static String decrypt(String data) throws Exception {
        Key k = toKey(Base64.decodeBase64(keyHex));
        AlgorithmParameterSpec iv = new IvParameterSpec(Base64.decodeBase64(ivHex));
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, k,iv);
        return new String(cipher.doFinal(Base64.decodeBase64(data)));
    }

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

        String encryptData = encrypt(source);
        System.out.println("加密: " + encryptData);

        String decryptData = decrypt(encryptData);
        System.out.println("解密: " + decryptData);
    }
}

这样就保证了前端加密的在后端也能解密

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值