【算法】AES前端加解密,Java后端加解密,采用CBC模式

适用范围:
1、前端加密、解密
2、后端加密、解密
3、前端加密、后端解密
4、后端加密、前端解密

前端AES

import CryptoJS from 'crypto-js'
import moment from 'moment'

let key = CryptoJS.enc.Utf8.parse('abcdefg123456789') // key:必须16个字符
let iv = CryptoJS.enc.Utf8.parse('abcdefg123456789'); // 偏移量:必须16个字符

// AES加密
function encrypt(data) {
     
  let encrypted = CryptoJS.AES.encrypt(data, key, {
     
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  // 返回的是base64格式的密文
  return encrypted.ciphertext.toString().toUpperCase();
}

// AES解密
function decrypt(data) {
     
  let encryptedHexStr = CryptoJS.enc.Hex.parse(data);
  let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypted = CryptoJS.AES.decrypt(srcs, key, {
     
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  let decryptedStr = decrypted.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}

module.exports = {
     
  encrypt: encrypt,
  decrypt: decrypt
}

Java后端AES

/**
 * AES工具类
 *
 * @author xiegege
 * @date 2020/11/12 10:15
 */
public class AESUtil {
     

   private final static String KEY = "abcdefg123456789"; // key:必须16个字符
   private final static String IV = "abcdefg123456789";  // 偏移量:必须16个字符

   public static void main(String[] args) {
     
        String content = "谢哥哥666";
        //加密
        String encrypted = encrypt(content);
        //解密
        String decrypted = decrypt(encrypted);
        System.out.println("加密前:" + content);
        System.out.println("加密后:" + encrypted);
        System.out.println("解密后:" + decrypted);
    }

    /**
     * 加密返回的数据转换成 String 类型
     *
     * @param content 明文
     */
    public static String encrypt(String content) {
     
        return parseByte2HexStr(Objects.requireNonNull(aesCbcEncrypt(content.getBytes(), KEY.getBytes(), IV.getBytes())));
    }

    /**
     * 将解密返回的数据转换成 String 类型
     *
     * @param content Base64编码的密文
     */
    public static String decrypt(String content) {
     
        return new String(Objects.requireNonNull(aesCbcDecrypt(parseHexStr2Byte(content), KEY.getBytes(), IV.getBytes())));
    }

    private static byte[] aesCbcEncrypt(byte[] content, byte[] keyBytes, byte[] iv) {
     
        try {
     
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
            return cipher.doFinal(content);
        } catch (Exception e) {
     
            System.out.println("exception:" + e.toString());
        }
        return null;
    }

    private static byte[] aesCbcDecrypt(byte[] content, byte[] keyBytes, byte[] iv) {
     
        try {
     
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            return cipher.doFinal(content);
        } catch (Exception e) {
     
            System.out.println("exception:" + e.toString());
        }
        return null;
    }

    /**
     * 将byte数组转换成16进制String
     */
    public static String parseByte2HexStr(byte[] buf) {
     
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
     
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
     
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制String转换为byte数组
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
     
        if (hexStr.length() < 1) {
     
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
     
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}

注意:前后端相互加解密时,前后端的key与iv需要保持一致

1、前端加密、解密

console.log("加密:" + AESUtil.encrypt("谢哥哥666"));
console.log("解密:" + AESUtil.decrypt(AESUtil.encrypt("谢哥哥666")));

在这里插入图片描述

2、后端加密、解密

public static void main(String[] args) {
     
    String content = "谢哥哥666";
    //加密
    String encrypted = encrypt(content);
    //解密
    String decrypted = decrypt(encrypted);
    System.out.println("加密前:" + content);
    System.out.println("加密后:" + encrypted);
    System.out.println("解密后:" + decrypted);
}

在这里插入图片描述

3、前端加密、后端解密

// 前端加密
console.log("加密:" + AESUtil.encrypt("谢哥哥666")); // 5FF2C0CC083FCD5F4F548CEF2846B95D
public static void main(String[] args) {
     
    // 后端解密
    String decrypted = decrypt("5FF2C0CC083FCD5F4F548CEF2846B95D");
    System.out.println("解密后:" + decrypted); // 谢哥哥666
}

4、后端加密、前端解密

public static void main(String[] args) {
     
    String content = "谢哥哥666";
    // 后端加密
    String encrypted = encrypt(content);
    System.out.println("加密前:" + content); // 谢哥哥666
    System.out.println("加密后:" + encrypted); // 5FF2C0CC083FCD5F4F548CEF2846B95D
}
// 前端解密
console.log("解密:" + AESUtil.decrypt("5FF2C0CC083FCD5F4F548CEF2846B95D")); // 谢哥哥666

总结

如果觉得不错,可以点赞+收藏或者关注下博主。感谢阅读!

你可能感兴趣的:(Java算法,一些工具类,JS算法,前端,javascript,java,安全,算法)