使用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 实现类如何配置,这里不再赘述。

猜你喜欢

转载自blog.csdn.net/hou_ge/article/details/132805357