AES 加解密(包含JS、VUE、JAVA、MySQL)工具方法

介绍

AES 是 Advanced Encryption Standard 的缩写,是最常见的对称加密算法。AES 在密码学中又称 Rijndael 加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的 DES,已经被多方分析且广为全世界所使用。

基本原理:AES 的加密公式为 C=E(K,P),其中 K 为密钥,P 为明文,C 为密文。

加密流程图:

封装工具方法

JS 工具方法

js 复制代码
// 引入依赖
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

// 加密方法
function encrypt(content, key) {
    return CryptoJS.AES.encrypt(content, CryptoJS.enc.Utf8.parse(key), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    }).ciphertext.toString();
}

// 解密方法
function decrypt(content, key) {
    return CryptoJS.AES.decrypt(CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(content)), CryptoJS.enc.Utf8.parse(key), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    }).toString(CryptoJS.enc.Utf8);
}

例子:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
    <script>
        var key = "xxxxxxxxxxxxxxxx";
        function encryptText() {
            var plain = document.getElementById("plain").value;
            var encrypted = encrypt(plain, key);
            document.getElementById("encrypted").value = encrypted;
        }

        function decryptText() {
            var encrypted = document.getElementById("todecrypt").value;
            var decrypted = decrypt(encrypted, key);
            document.getElementById("decrypted").value = decrypted;
        }

        // 加密方法
        function encrypt(content, key) {
            return CryptoJS.AES.encrypt(content, CryptoJS.enc.Utf8.parse(key), {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            }).ciphertext.toString();
        }

        // 解密方法
        function decrypt(content, key) {
            return CryptoJS.AES.decrypt(CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(content)), CryptoJS.enc.Utf8.parse(key), {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            }).toString(CryptoJS.enc.Utf8);
        }
    </script>
</head>
<body>
    <h2>加解密测试</h2>
    <div  style="padding: 1rem 0">
        <input id="plain" type="text" />
        <button type="button" onclick="encryptText()">加密</button>
        <input id="encrypted" type="text"/>
    </div>
    <div>
        <input id="todecrypt" type="text"/>
        <button type="button" onclick="decryptText()">解密</button>
        <input id="decrypted" type="text"/>
    </div>
</body>
</html>

VUE 工具方法

js 复制代码
// 添加依赖
npm install crypto-js

// 加密方法
function onEncrypt(content: any, key: any) {
  return CryptoJS.AES.encrypt(content, CryptoJS.enc.Utf8.parse(key), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).ciphertext.toString().toUpperCase();
}

// 解密方法
function onDecrypt(content: any, key: any) {
  return CryptoJS.AES.decrypt(
    CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(content)), CryptoJS.enc.Utf8.parse(key), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }
  ).toString(CryptoJS.enc.Utf8);
}

例子:

js 复制代码
<script setup lang="ts">
import { onMounted, reactive, toRefs } from "vue";
import CryptoJS from "crypto-js";

const state = reactive({
    key: "xxxxxxxxxxxxxxxx",
    plain: null,
    encrypted: null,
    todecrypt: null,
    decrypted: null
})
const {key,plain,encrypted,todecrypt,decrypted} = toRefs(state)


function encryptText() {
    state.encrypted = onEncrypt(state.plain, state.key);
}

function decryptText() {
    state.decrypted = onDecrypt(state.todecrypt, state.key);
}

// 加密方法
function onEncrypt(content: any, key: any) {
  return CryptoJS.AES.encrypt(content, CryptoJS.enc.Utf8.parse(key), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).ciphertext.toString().toUpperCase();
}

// 解密方法
function onDecrypt(content: any, key: any) {
  return CryptoJS.AES.decrypt(
    CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(content)), CryptoJS.enc.Utf8.parse(key), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }
  ).toString(CryptoJS.enc.Utf8);
}
</script>
<template>
  <div class="aes">
    <h1>AES加解密</h1>
    <el-row :gutter="20" style="padding: 1rem 0">
        <el-col :span="6"><el-input v-model="plain" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="2"><el-button type="primary" @click="encryptText()">加密</el-button></el-col>
        <el-col :span="12"><div>{{state.encrypted}}</div></el-col>
    </el-row>
    <el-row :gutter="20">
        <el-col :span="6"><el-input v-model="todecrypt" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="2"><el-button type="primary" @click="decryptText()">解密</el-button></el-col>
        <el-col :span="12"><div>{{state.decrypted}}</div></el-col>
    </el-row>
  </div>
</template>
<style lang="scss" scoped>
.aes {
  text-align: center;
}
</style>

JAVA 工具类

java 复制代码
package com.tansci.util;

import org.apache.commons.codec.binary.Hex;

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

/**
 * @ClassName: AESUtil.java
 * @ClassPath: com.tansci.util.AESUtil.java
 * @Description: AES对称加解密工具类
 * @Author: tanyp
 * @Date: 2024/4/18 12:00
 **/
public class AESUtil {
    
    /**
     * @MonthName: encrypt
     * @Description: 加密
     * @Author: tanyp
     * @Date: 2024/4/18 12:00
     * @Param: [content, key: 16位]
     * @return: java.lang.String
     **/
    public static String encrypt(String content, String key) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        return Hex.encodeHexString(b);
    }

    /**
     * @MonthName: decrypt
     * @Description: 解密
     * @Author: tanyp
     * @Date: 2024/4/18 12:00
     * @Param: [encryptStr, key:16位]
     * @return: java.lang.String
     **/
    public static String decrypt(String encryptStr, String key) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        byte[] encrypttBytes = Hex.decodeHex(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encrypttBytes);
        return new String(decryptBytes);
    }

}

MYSQL 使用方法

sql 复制代码
-- 加密 
select HEX(AES_ENCRYPT('admin','xxxxxxxxxxxxxxxx'))

-- 解密  
select CONVERT(AES_DECRYPT(UNHEX('305e188e6818582f8298551e4b50702a'),'xxxxxxxxxxxxxxxx') USING UTF8MB4)
select AES_DECRYPT(UNHEX('4C80D7BE4719ED572565378025E7AC85'),'xxxxxxxxxxxxxxxx')
  
相关推荐
hong_zc1 小时前
算法【Java】—— 二叉树的深搜
java·算法
进击的女IT2 小时前
SpringBoot上传图片实现本地存储以及实现直接上传阿里云OSS
java·spring boot·后端
Miqiuha2 小时前
lock_guard和unique_lock学习总结
java·数据库·学习
一 乐3 小时前
学籍管理平台|在线学籍管理平台系统|基于Springboot+VUE的在线学籍管理平台系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习
昨天;明天。今天。3 小时前
案例-表白墙简单实现
前端·javascript·css
数云界3 小时前
如何在 DAX 中计算多个周期的移动平均线
java·服务器·前端
安冬的码畜日常3 小时前
【玩转 JS 函数式编程_006】2.2 小试牛刀:用函数式编程(FP)实现事件只触发一次
开发语言·前端·javascript·函数式编程·tdd·fp·jasmine
阑梦清川3 小时前
Java继承、final/protected说明、super/this辨析
java·开发语言
小御姐@stella3 小时前
Vue 之组件插槽Slot用法(组件间通信一种方式)
前端·javascript·vue.js
GISer_Jing3 小时前
【React】增量传输与渲染
前端·javascript·面试