AES cbc前后端加密

  • Post author:
  • Post category:其他


直接上代码

一.前端

import CryptoJS from 'crypto-js';
	/**
 * 加密解密
 *`在这里插入代码片`
 * @type {string}
 */
// const key = '*1smurfs*';
const key = '1234567812345678';
const iv = '1234567812345678';
export function getKey() {
  // 真正的key
  return CryptoJS.enc.Utf8.parse(key);
}

export function getIv() {
  // 真正的iv
  return CryptoJS.enc.Utf8.parse(iv);
}
export function encrypt(data) {
  // console.log(getKey(key));
  // let encrypt = CryptoJS.AES.encrypt(data, CryptoJS.enc.Hex.parse(getKey(key)), {
  //   mode: CryptoJS.mode.ECB,
  //   padding: CryptoJS.pad.Pkcs7
  // })
  // const message = CryptoJS.enc.Utf8.parse(data);
  var ciphertext = CryptoJS.AES.encrypt(data, getKey(), {
    iv: getIv(),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return ciphertext.toString();
  // return CryptoJS.AES.encrypt(data, getKey(), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString();
}

export function decrypt(data) {
  var bytes = CryptoJS.AES.decrypt(data.toString(), getKey(), {
    iv: getIv(),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return bytes.toString(CryptoJS.enc.Utf8);
  // const decrypt = CryptoJS.AES.decrypt(data, getKey(key), {
  //   mode: CryptoJS.mode.ECB,
  //   padding: CryptoJS.pad.Pkcs7
  // });
  // return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

二.后端代码

package com.jgtl.smurfs.modules.util;


import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

/**
 * @Description:
 * @ClassName AESpkcs7paddingUtil
 * @date: 2020.11.06 16:04
 * @Author: lvyp
 */

public class AESpkcs7paddingUtil {
    //使用AES-128-CBC加密模式,key需要为16位,key和iv可以相同!
    /**
     * 密钥算法
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * 加密/解密算法 / 工作模式 / 填充方式
     * Java 6支持PKCS5Padding填充方式
     * Bouncy Castle支持PKCS7Padding填充方式
     */
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

    /**
     * 偏移量,只有CBC模式才需要
     */
    private final static String ivParameter = "1234567812345678";


    /**
     * AES要求密钥长度为128位或192位或256位,java默认限制AES密钥长度最多128位
     */
    public static String sKey = "";

    /**
     * 编码格式
     */
    public static final String ENCODING = "utf-8";


    static {
        //如果是PKCS7Padding填充方式,则必须加上下面这行
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES加密
     *
     * @param source 源字符串
     * @param
     * @throws Exception
     * @return 加密后的密文
     */
    public static String encrypt(String source, String key) throws Exception {
        byte[] sourceBytes = source.getBytes(ENCODING);
        byte[] keyBytes = key.getBytes(ENCODING);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes(ENCODING));
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM), iv);
        byte[] decrypted = cipher.doFinal(sourceBytes);
        return Base64.encodeBase64String(decrypted);
    }

    /**
     * AES解密
     *
     * @param encryptStr 加密后的密文
     * @param
     * @throws Exception
     * @return 源字符串
     */
    public static String decrypt(String encryptStr, String key) throws Exception {
        byte[] sourceBytes = Base64.decodeBase64(encryptStr);
        byte[] keyBytes = key.getBytes(ENCODING);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes(ENCODING));
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM), iv);
        byte[] decoded = cipher.doFinal(sourceBytes);
        return new String(decoded, ENCODING);
    }


    public static void main(String[] args) throws Exception {
        String key = "1234567812345678";

        // 加密
        long lStart = System.currentTimeMillis();
        String enString = AESpkcs7paddingUtil.encrypt("Aes cbc 中文测试加标点符号!@#¥%……&*(+——)", key);
        System.out.println("加密后的字串是:" + enString);

        long lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("加密耗时:" + lUseTime + "毫秒");

        // 解密
        lStart = System.currentTimeMillis();
        String DeString = AESpkcs7paddingUtil.decrypt(enString , key);
        System.out.println("解密后的字串是:" + DeString);
        lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("解密耗时:" + lUseTime + "毫秒");
    }

}

以上是前后端加密的代码,测试OK!



版权声明:本文为weixin_45818787原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。