前言

前后端加密解密的方式有很多,此使用CryptoJs进行Aes加密解密,

官方文档有介绍

引入依赖

<!--引入  AES/ECB/PKCS7Padding  支持-->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>

java代码:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.security.Security;

/**
 * @authoer:majinzhong
 * @Date: 2022/11/24
 * @description:
 */
@Slf4j
public class AESUtil {

    /**
     * AES加密
     *
     * @param content 明文
     * @param key     秘钥
     * @return
     * @throws Exception
     */
    public static String encrypt(Object content, String key) throws Exception {
        String s ="";
        //判断content是否为字符串
        if(content instanceof String){
            s=content.toString();
        }else {
            s = JSONUtil.parse(content).toString();
        }
        // 将返回的加密过的 byte[] 转换成Base64编码字符串 !!!!很关键
        return base64ToString(AES_ECB_Encrypt(s.getBytes(), key.getBytes()));
    }

    /**
     * AES解密
     *
     * @param content Base64编码的密文
     * @param key     秘钥
     * @return
     * @throws Exception
     */
    public static Object decrypt(String content, String key) {
        // stringToBase64() 将 Base64编码的字符串转换成 byte[] !!!与base64ToString()配套使用
        try {
            byte[] base64 = stringToBase64(content);
            byte[] bytes = AES_ECB_Decrypt(base64, key.getBytes());
            String result = new String(bytes);
            String s = result.replaceAll("\"", "");
            //判断解密出来的数据是字符串还是json
            if(s.startsWith("{") && s.endsWith("}")){
                JSON parse = JSONUtil.parse(s);
                return parse;
            }else{
                return s;
            }
        } catch (Exception e) {
            log.info("AES解密出错!!!");
            e.printStackTrace();
        }

        return null;
    }

    private static byte[] AES_ECB_Encrypt(byte[] content, byte[] keyBytes) {
        try {
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] AES_ECB_Decrypt(byte[] content, byte[] keyBytes) {
        try {
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串装换成 Base64
     */

    public static byte[] stringToBase64(String key) throws Exception {
        return Base64.decodeBase64(key.getBytes());
    }

    /**
     * Base64装换成字符串
     */
    public static String base64ToString(byte[] key) throws Exception {
        return new Base64().encodeToString(key);
    }

    public static void main(String[] args) throws Exception {
        String key = "8F6B2AK33DZE20A05E74C231B47AC8F9";//加密密钥,很关键,不要对外泄露哦

        String content = "hello";//明文

        String end = encrypt(content, key);
        System.out.println("加密:" + end);

        String decrypt = decrypt("hxHR5CwCA6n2OuDWcq1SIA==", key).toString();
        System.out.println("解密:"+decrypt);
    }
}


前端js

引入依赖

npm install crypto-js -S

完整代码

import CryptoJS from 'crypto-js';

const key= "8F6B2AK33DZE20A05E74C231B47AC8F9"
/**
 * 加密 --api
 * @param word string
 * @returns {*} string
 */
 export function cipherText(word){//word 为 string  mode为加密规则
    var secretKey = CryptoJS.enc.Utf8.parse(key);//key  为你的秘钥
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, secretKey, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}
/**
 * 解密 --api
 * @param word string
 * @returns {*} string
 */
export function decrypted(word){
    var secretKey = CryptoJS.enc.Utf8.parse(key);
    var decrypt = CryptoJS.AES.decrypt(word, secretKey, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

补充:vue可以直接引入CryptoJS,制作不要求密钥长度的AES加密,但是传递的简短的字符串不是用于加密的密钥,而是根据这个字符串生成了实际的密钥、盐和向量用于加密。所以需要前后端规定密钥传输,且密钥长度不能低于16位

AES——CBC模式加密解密
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Decryptor {

    public static String decrypt(String toDecrypt, String key, String iv) throws Exception {

        byte[] keyArray = key.getBytes(StandardCharsets.UTF_8);
        byte[] ivArray = iv.getBytes(StandardCharsets.UTF_8);
        byte[] toEncryptArray = Base64.getDecoder().decode(toDecrypt);

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyArray, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivArray);

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] resultArray = cipher.doFinal(toEncryptArray);

        return new String(resultArray, StandardCharsets.UTF_8);
    }

    public static String encrypt(String toEncrypt, String key, String iv) throws Exception {

        byte[] keyArray = key.getBytes(StandardCharsets.UTF_8);
        byte[] ivArray = iv.getBytes(StandardCharsets.UTF_8);
        byte[] toEncryptArray = toEncrypt.getBytes(StandardCharsets.UTF_8);

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyArray, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivArray);

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] resultArray = cipher.doFinal(toEncryptArray);

        return Base64.getEncoder().encodeToString(resultArray);
    }

    public static void main(String[] args) throws Exception {

        String encryptedText = "XfuRtlLwjLGnwKuTIp36GNfgUk3UzHMDFixdIxC2DXCJpndy7pZkuDROILBjeKRSr78kwtfyzCKMXDUUpZjsnIPq1FuA/mjbZZ39fOxK7UmLmjFrtCs83j1yskKiJIHMCAm1cKtUM0RAb9FrAXCSu9Jjf9WU/8+PYy20DCgkkZpmXtN0X8sP83Euv5E+p5L8SrMFZ+9q3+DKTZIvKV0Dro/9H5mwyA2ARo/LSUDYx4GBpmeldh1IpHynk8ksmNWFT7RoptJdezSDU6V126LDvZNZ6vhZ5zPI9mwcgDnhJfwn5OFX1NkhldAQTtt8HOjsWZYxOkOgjtd/eaX/EJl/fLJ3AwcrA1uYDaT8RH3zz511jStGM2dwEd321DPExejofdv6HMqM71k6hZrAH/1FTZTNuRrh/Oy1fVfyMBPJ/L3i0siKaw/HLH/YQkmwQPZUX/712de9qTayXF9uvw5SYVjdqQzvUdnPVgi9mmZcfv+EGq6ccslQtG0mR7uicHA98FqEK5TE32I/Tzn0QDhv98eOqif0Kli2Kn1QcAmidl2h+kAKbjjjivlMoeGBSiSI1kU+ueR1hG/ilNLcwNZNfHpdEUPXVZxS8CvkEwtcVAM=";
        String key = "DMK53068HYTBED78";
        String iv = "32C65ASD1C9EB6D0";

        System.out.println(decodedData);
        String decryptedText = decrypt(decodedData, key, iv);
        System.out.println("Decrypted text: " + decryptedText);

        String encrypt = encrypt(decryptedText, key, iv);
        System.out.println(encrypt);
    }
}

再次补充,如果加密之后的数据是通过GET方式传过来的,则需要URL解码

//编码
URLEncoder.encode(urlToken, "UTF-8")
//解码
URLDecoder.decode(urlToken, String.valueOf(StandardCharsets.UTF_8));

遇到的问题,加密时,可能会报Input length not multiple of 16 bytes的异常

这是因为需要加密的数据,没有被16整除,要避免这个问题,需要对数据进行适当的填充,通常使用密码学库提供的填充模式来实现,例如PKCS5Padding、PKCS7Padding或ZeroPadding。

修改如下代码即可

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

再再次补充

如果还是想用NoPadding方式,但是需要加密的参数不是16的倍数,那就需要用到hutool工具类了

引入依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.0</version>
        </dependency>

代码如下

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * AES加密,解密(CBC模式)
 */
public class AESUtil {
    /**
     * 加密
     * @param toEncrypt
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    public static String encrypt(String toEncrypt, String key, String iv) throws UnsupportedEncodingException {
        AES aes = new AES(Mode.CBC, Padding.NoPadding, key.getBytes(), iv.getBytes());
        byte[] plainBytes = toEncrypt.getBytes();
        int paddingLength = 16 - (plainBytes.length % 16);
        byte[] paddedPlainBytes = new byte[plainBytes.length + paddingLength];
        System.arraycopy(plainBytes, 0, paddedPlainBytes, 0, plainBytes.length);
        byte[] encrypt = aes.encrypt(paddedPlainBytes);
//        return Base64.encode(encrypt)
        //需要对token进行url编码
        return URLEncoder.encode(Base64.encode(encrypt), String.valueOf(StandardCharsets.UTF_8));
    }

    /**
     * 解密
     * @param toDecrypt
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    public static String decrypt(String toDecrypt, String key, String iv) throws UnsupportedEncodingException {
        //需要对token进行url解码
        String decodedData = URLDecoder.decode(toDecrypt, String.valueOf(StandardCharsets.UTF_8));

        AES aes = new AES(Mode.CBC, Padding.NoPadding, key.getBytes(), iv.getBytes());
        byte[] encryptedBytes = Base64.decode(decodedData);
        byte[] decrypt = aes.decrypt(encryptedBytes);
        // 去除填充字符
        int paddingLength = decrypt[decrypt.length - 1];
        byte[] plainBytes = new byte[decrypt.length - paddingLength];
        System.arraycopy(decrypt, 0, plainBytes, 0, plainBytes.length);
        return new String(plainBytes);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        // 密钥,长度为16个字符(128位), 24个字符(192位)或 32个字符(256位)
        String key = "DMK53068HYTBED78";
        // 初始化向量,长度为16个字符
        String iv = "32C65ASD1C9EB6D0";
        // 待加密的文本
        String plainText = "Hello, World!";

        // 加密
        String encryptedText = encrypt(plainText, key, iv);
        System.out.println("Encrypted Text: " + encryptedText);

        // 解密
        String decryptedText = decrypt(encryptedText, key, iv);

        System.out.println("Decrypted Text: " + decryptedText);
    }
}

这样就解决了AES的CBC模式NoPadding下需要加密的参数不是16的倍数的问题。

Logo

前往低代码交流专区

更多推荐