对称加密工具类(前后端)

前端加密需要引入crypto-js库,crypto-js是加密标准的JavaScript库,实现了各种加密算法,使用node安装
* npm install crypto-js --save
 const CryptoJS = require('crypto-js');

 //十六位十六进制数作为密钥
     const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF");
     
      //解密方法
      function Decrypt(word) {
        let decrypt = CryptoJS.AES.decrypt(word, key, { mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
        let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
      }
     
      //加密方法
     function Encrypt(word) {
        let srcs = CryptoJS.enc.Utf8.parse(word);
        let encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
        return encrypted.toString();
      }
     
      export {
        Decrypt,
        Encrypt
      }
     

 后端加密工具类:

public class AesUtils {
 /** 密钥长度: 128, 192 or 256 */
    private static final int KEY_SIZE = 128;

    /**
     * 加密/解密算法名称
     */
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
    /**
     * 秘钥算法
     */
    private static final String KEY_ALGORITHM = "AES";
    /**
     * 十六位十六进制数作为密钥
     */
    private static final String key = "1234123412ABCDEF";

    /**
     * 秘钥对象
     */
    private static final SecretKey secKey = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);

    /**
     * 数据加密: 明文 -> 密文
     */
    public static String encrypt(String plainString) throws Exception {
        // 获取 AES 密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        // 初始化密码器(加密模型)
        cipher.init(Cipher.ENCRYPT_MODE, secKey);
        // 加密数据, 返回密文,使用base64编码密文byte数组,返回密文字符串
        return new String(Base64.getEncoder().encode(cipher.doFinal(plainString.getBytes("utf-8"))));
    }

    /**
     * 数据解密: 密文 -> 明文
     */
    public static String decrypt(String cipherString) throws Exception {
        // 获取 AES 密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        // 初始化密码器(解密模型)
        cipher.init(Cipher.DECRYPT_MODE, secKey);
        // 解密数据, 返回明文,对base64编码的密文解码成密文byte数组,再使用AES解码
        byte[] plainBytes = cipher.doFinal(Base64.getDecoder().decode(cipherString));
        return new String(plainBytes);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值