使用CryptoJS实现Vue前端加密,Java后台解密的步骤和方法

1、crypto.js简介

  CryptoJS 是一个 JavaScript 库,提供了一系列密码学函数和工具,用于加密、解密、生成摘要等任务。它支持多种加密算法,包括常见的对称加密算法(如 AES、DES)和非对称加密算法(如 RSA)。
  同时,CryptoJS还包括了ECB和CBC两种模式,其中ECB模式:全称Electronic Codebook(电码本),在ECB模式中,每个明文分组都被单独加密,且每个明文分组都被加密为相同的密文分组。也就是说,如果两个明文分组相同,那么它们的密文分组也相同。CBC模式:全称Cipher Block Chaining(密文分组链接模式),在CBC模式中,每个明文分组都与前一个密文分组进行XOR运算(相异为一)然后再进行加密。因此,密文分组是相互连接的,如果两个明文分组相同,那么它们的密文分组也会不同。
  这里,我们使用了AES对称加密算法,并使用了CBC模式实现登录密码的加密,实现步骤如下:

2、Vue前端步骤

2.1、安装CryptoJS
npm install crypto-js
2.2、引入CryptoJS
import CryptoJS from 'crypto-js';
2.3、加密方法
//设置秘钥和秘钥偏移量
const SECRET_KEY = CryptoJS.enc.Utf8.parse("1234567890123456");
const SECRET_IV = CryptoJS.enc.Utf8.parse("1234567890123456");
/**
 * 加密方法
 * @param word
 * @returns {string}
 */
function encrypt(word) {
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, SECRET_KEY, {
      iv: SECRET_IV ,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
  })
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}
2.4、解密方法

  该方法,在前端一般是不需要的,前端只需要使用加密方法进行加密即可。

function decrypt(word) {
  let base64  = CryptoJS.enc.Base64.parse(word);
  let srcs = CryptoJS.enc.Base64.stringify(base64);
  const decrypt = CryptoJS.AES.decrypt(srcs, SECRET_KEY, {
    iv: SECRET_IV ,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  });
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr;
}

3、Java实现解密的工具类

  CryptoUtil 工具类提供了基于前端CryptoJS一致的加密和解密方法,在后端主要使用到的其中的解密方法。


/**
 * Description: 配合前端CryptoJS实现加密、解密工作。
 * CryptoJS 是一个 JavaScript 库,提供了一系列密码学函数和工具,用于加密、解密、生成摘要等任务。
 * 它支持多种加密算法,包括常见的对称加密算法(如 AES、DES)和非对称加密算法(如 RSA)。
 */
public class CryptoUtil {

    private final static String IV = "1234567890123456";//需要前端与后端配置一致
    private final static String KEY = "1234567890123456";

    /**
     * 加密算法,使用默认的IV、KEY
     * @param content
     * @return
     */
    public static String encrypt(String content){
        return encrypt(content,KEY,IV);
    }

    /**
     * 解密算法,使用默认的IV、KEY
     * @param content
     * @return
     */
    public static String decrypt(String content){
        return decrypt(content,KEY,IV);
    }
    /**
     * 加密方法
     * @param content
     * @param key
     * @param iv
     * @return
     */
    public static String encrypt(String content, String key, String iv){
        try{
            // "算法/模式/补码方式"NoPadding PkcsPadding
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = content.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("UTF-8"), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("UTF-8"));
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new Base64().encodeToString(encrypted);
        }catch (Exception e) {
            throw new RuntimeException("加密算法异常 CryptoUtil encrypt()加密方法,异常信息:" + e.getMessage());
        }
    }

    /**
     * 解密方法
     * @param content
     * @param key
     * @param iv
     * @return
     */
    public static String decrypt(String content, String key, String iv){
        try {
            byte[] encrypted1 = new Base64().decode(content);
            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);
            return new String(original).trim();
        } catch (Exception e) {
            throw new RuntimeException("加密算法异常 CryptoUtil decrypt()解密方法,异常信息:" + e.getMessage());
        }
    }
}

4、在SpringSecurity项目中如何使用CryptoUtil 解密工具类

  不同项目用户密码存储方式,登录密码校验都有自己的逻辑,在我的项目里,我使用了SpringSecurity框架作为鉴权,同时基于MD5实现了PasswordEncoder接口(QriverMD5PasswordEncoder),其中使用了DigestUtils.md5DigestAsHex()方法对用户登录密码进行了加密保存。因此,我在PasswordEncoder接口的实现方法matches()中,实现了前端传递密码的解密,然后再进行MD5加密后,参与到密码的对比。QriverMD5PasswordEncoder的实现如下:


/**
 * PasswordEncoder实现类,从5.0版本开始强制要求设置,主要用来配置加密方式
 */
@Component("md5PasswordEncoder")
public class QriverMD5PasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return DigestUtils.md5DigestAsHex(rawPassword.toString().getBytes());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
    	//前端登录密码解密
        String deRawPassword = CryptoUtil.decrypt(rawPassword.toString());
        String encode = DigestUtils.md5DigestAsHex(deRawPassword.toString().getBytes());
        return encodedPassword.equals( encode );
    }

    public static void main(String[] args) {
        String rawPassword = "EVFon/Y9ed2W/0zc6iQlkg==";
        System.out.println(CryptoUtil.decrypt(rawPassword.toString()));
    }
}

  至此就完成了前端加密传递登录密码,后端解密使用密码,同时也保证了登录密码MD5加密存在数据库中,关于PasswordEncoder 实现类如何配置,这里不再赘述。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
前端Vue传递加密密文到后端Java,后解密的示例代码如下: 前端Vue加密代码: ```javascript // 导入jsencrypt库 import JSEncrypt from 'jsencrypt' // 创建RSA加密实例 const encrypt = new JSEncrypt() // 设置RSA公钥 const publicKey = 'YOUR_RSA_PUBLIC_KEY' encrypt.setPublicKey(publicKey) // 要加密的数据 const data = 'YOUR_DATA_TO_ENCRYPT' // 使用RSA公钥进行加密 const encryptedData = encrypt.encrypt(data) // 将加密后的数据发送到后端 // 例如使用axios发送POST请求 axios.post('/api/decrypt', { encryptedData }) .then(response => { console.log(response.data) }) .catch(error => { console.error(error) }) ``` 后端Java解密代码: ```java import org.apache.commons.codec.binary.Base64; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.crypto.Cipher; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.PKCS8EncodedKeySpec; @RestController public class DecryptionController { // 将Base64编码后的私钥字符串转换为PrivateKey对象 private PrivateKey getPrivateKey(String privateKeyStr) throws Exception { byte[] privateKeyBytes = Base64.decodeBase64(privateKeyStr); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); } @PostMapping("/api/decrypt") public String decryptData(@RequestBody EncryptedData encryptedData) throws Exception { String privateKeyStr = "YOUR_RSA_PRIVATE_KEY"; PrivateKey privateKey = getPrivateKey(privateKeyStr); // 使用私钥进行解密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] encryptedBytes = Base64.decodeBase64(encryptedData.getEncryptedData()); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); // 返回解密后的数据 return new String(decryptedBytes, StandardCharsets.UTF_8); } } ``` 创建一个名为 `EncryptedData` 的Java类,用于接收前端传递的加密数据: ```java public class EncryptedData { private String encryptedData; public String getEncryptedData() { return encryptedData; } public void setEncryptedData(String encryptedData) { this.encryptedData = encryptedData; } } ``` 请将 `YOUR_RSA_PUBLIC_KEY` 替换为你的RSA公钥,将 `YOUR_RSA_PRIVATE_KEY` 替换为你的RSA私钥。在前端,你可以使用axios或其他HTTP库发送POST请求到后端的 `/api/decrypt` 路径,并将加密后的数据作为请求体的 `encryptedData` 字段传递。后端将解密后的数据作为响应返回给前端

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姠惢荇者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值