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

11 篇文章 0 订阅
3 篇文章 0 订阅

介绍

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

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

加密流程图:
在这里插入图片描述

封装工具方法

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);
}

例子:

<!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 工具方法

// 添加依赖
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);
}

例子:

<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 工具类

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 使用方法

-- 加密 
select HEX(AES_ENCRYPT('admin','xxxxxxxxxxxxxxxx'))

-- 解密  
select CONVERT(AES_DECRYPT(UNHEX('305e188e6818582f8298551e4b50702a'),'xxxxxxxxxxxxxxxx') USING UTF8MB4)
select AES_DECRYPT(UNHEX('4C80D7BE4719ED572565378025E7AC85'),'xxxxxxxxxxxxxxxx')
  
  • 23
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值