springboot接口验签,前后端加解密(基于hutool)、c#、vue、js的aes指定秘钥加密(前后端aes加解密)

gitee源码地址:https://gitee.com/huangtao_2021/springboot-encrypt.git,加解密基础上增加了接口注解验签功能,c#、vue、js版本的代码放在项目路径下/src/main/java/resources文件夹中

 

 


一、后端java

 //aes加密,输出16进制
String jsondata = SecureUtil.aes("._^BV67nW6ck8fwg".getBytes()).encryptHex(obj);
System.out.println(jsondata);

//aes解密密,输出16进制
String decryptStr = SecureUtil.aes("._^BV67nW6ck8fwg".getBytes()).decryptStr(jsondata);
System.out.println(decryptStr);
 

 gitee源码地址:https://gitee.com/huangtao_2021/springboot-encrypt.git,加解密基础上增加了接口注解验签功能

二、后端c#

 

        ///// <summary>
        /// 测试aes
        ///// </summary>
        public void test()
        {
            try
            {
                var b = "k3RA2bS97JlV5XPEueiqUA==";
                var c = AesEncryptor_Hex("中国test", "._^BV67nW6ck8fwg");
                var d = AesDecryptor_Hex(c, "._^BV67nW6ck8fwg");
            }
            catch (Exception ec)
            {
                throw ec;
            }
        }






using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;


namespace StrongOA.Core.Utils
{
public class AESHelper
{
/// <summary>
///AES 算法加密(ECB模式) 将明文加密,加密后进行Hex编码,返回密文
/// </summary>
/// <param name="str">明文</param>
/// <param name="key">密钥</param>
/// <returns>加密后Hex编码的密文</returns>
public static string AesEncryptor_Hex(string input, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 16));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Mode = CipherMode.ECB;
aesAlg.Key = keyBytes;
aesAlg.IV = keyBytes;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(input);
}
byte[] bytes = msEncrypt.ToArray();
var hexStr = ByteArrayToHexString(bytes).ToLower();
return hexStr;
}
}
}
}


/// <summary>
///AES 算法解密(ECB模式) 将密文Hex解码后进行解密,返回明文
/// </summary> AesDecryptor_Hex
/// <param name="str">密文</param>
/// <param name="key">密钥</param>
/// <returns>明文</returns>
public static string AesDecryptor_Hex(string input, string key)
{
//byte[] inputBytes = Convert.FromBase64String(input);
byte[] inputBytes = HexStringToByteArray(input);
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 16));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Mode = CipherMode.ECB;
aesAlg.Key = keyBytes;
aesAlg.IV = keyBytes;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream(inputBytes))
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srEncrypt = new StreamReader(csEncrypt))
{
return srEncrypt.ReadToEnd();
}
}
}
}
}


/// <summary>
/// 字节数组转十进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
private static string ByteArrayToHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}


/// <summary>
/// 十进制字符串转字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private static byte[] HexStringToByteArray(string hexString)
{
if (hexString == null)
{
throw new ArgumentNullException(nameof(hexString));
}
if (hexString.Length % 2 != 0)
{
throw new ArgumentException("The binary key cannot have an odd number of digits");
}
byte[] data = new byte[hexString.Length / 2];
for (int i = 0; i < data.Length; i++)
{
string hex = hexString.Substring(i * 2, 2);
data[i] = Convert.ToByte(hex, 16);
}
return data;
}
}
}

 

 

 三、前端vue

utils文件夹下新建encryp.js

import CryptoJS from 'crypto-js'
// 加密
export default {
encrypt(word, keyStr, iv) {
let keys = CryptoJS.enc.Utf8.parse(keyStr); //'82LIb3DQE9ByIdz9'
let ivs = CryptoJS.enc.Utf8.parse(iv); //iv '0102030405060708'
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, keys, {
iv: ivs,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log("base64:" + encrypted);
var encryptedStr = encrypted.ciphertext.toString();
console.log("16进制:" + encryptedStr);
return encrypted.ciphertext.toString(); //16进制
// return encrypted.toString(); //base64
},
// }
// 解密
decrypt(word, keyStr, iv) {
// ********************解密16进制***********************
let key = CryptoJS.enc.Utf8.parse(keyStr); //'82LIb3DQE9ByIdz9'
let ivs = CryptoJS.enc.Utf8.parse(iv); //'0102030405060708'
let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
let decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: ivs,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
console.log(decryptedStr)
return decryptedStr.toString();
}

}

使用

import Crypto from "@/utils/encryp.js"; //很多页面要使用时也可以再main.js中定义:import Crypto from "@/utils/encryp.js";Vue.prototype.$crypto = Crypto; 页面中调用: var t = $crypto.encrypt('中国test',"._^BV67nW6ck8fwg","");



var encode = Crypto.encrypt('中国test',"._^BV67nW6ck8fwg","");
console.log("加密后:"+encode);

var decode = Crypto.decrypt('4aeb52befdb579c52889cb5e9678bea5',"._^BV67nW6ck8fwg","");
console.log("解密后:"+decode);

 

四、前端js
 

需要下载CryptoJS库,下载地址如下:
https://github.com/sytelus/CryptoJS

需要引入库文件:
<script src="./CryptoJS-master/rollups/aes.js"></script>
<script src="./CryptoJS-master/components/mode-ecb.js"></script>
<script src="./CryptoJS-master/components/pad-nopadding.js"></script>

 

以下是完整的Demo代码:

复制代码

<!DOCTYPE html>
<html>
<head>
<script src="aes-min.js"></script>
<script src="mode-ecb-min.js"></script>
<script src="pad-nopadding-min.js"></script>
<script>
function encryptText() {
var plain = document.getElementById("plain").value;
console.log("plain: " + plain);
var encrypted = encrypt(plain);
console.log("encrypted: " + encrypted);
document.getElementById("encrypted").value = encrypted;
}

function decryptText() {
var encrypted = document.getElementById("todecrypt").value;
console.log("encrypted: " + encrypted);
var decrypted = decrypt(encrypted);
console.log("decrypted: " + decrypted);
document.getElementById("decrypted").value = decrypted;
}

 


// 加密方法
// data:要加密的字符串
// key:加密因子
// iv:偏移量
function encrypt(data) {

var keyinit = "._^BV67nW6ck8fwg";
var ivinit = "";

var key = CryptoJS.enc.Utf8.parse(keyinit); // 加密因子
var iv = CryptoJS.enc.Utf8.parse(ivinit); // 偏移量
var str = CryptoJS.enc.Utf8.parse(data); // 使用的字符集 uft8
var encrypted = CryptoJS.AES.encrypt(str, key,
{
iv:iv,
mode:CryptoJS.mode.ECB, // AES加密模式
padding:CryptoJS.pad.Pkcs7 // 填充: pkcs7 padding
}).ciphertext.toString(); // 输出字符 hex
return encrypted;
}

// 解密方法
// data:要解密的字符串
// key:加密因子
// iv:偏移量
function decrypt(data) {

var key = "._^BV67nW6ck8fwg";
var iv = "";

var key = CryptoJS.enc.Utf8.parse(key); // 加密因子
var iv = CryptoJS.enc.Utf8.parse(iv); // 偏移量
const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
const str = CryptoJS.enc.Base64.stringify(encryptedHexStr) ;
const decrypted = CryptoJS.AES.decrypt(str, key,
{
iv:iv,
mode:CryptoJS.mode.ECB, // AES加密模式
padding:CryptoJS.pad.Pkcs7 // 填充: pkcs7 paddin
});
return decrypted.toString(CryptoJS.enc.Utf8).toString();
}

 

</script>
</head>
<body>
<h1>AES加解密测试</h1>
AES128,ECB模式,Pkcs7,iv为空,输出hex,utf8
<br>
<input id="plain" type="text" style="width:500px; height:20px;"/>
<button type="button" onclick="encryptText()">加密</button>
<input id="encrypted" type="text" style="width:500px; height:20px;" />
<br>
<br>
<br>
<input id="todecrypt" type="text" style="width:500px; height:20px;"/>
<button type="button" onclick="decryptText()">解密</button>
<input id="decrypted" type="text" style="width:500px; height:20px;" />
</body>
</html>

复制代码

在浏览器中打开之后效果如下:

 



posted on 2023-07-04 17:10  五官一体即忢  阅读(1252)  评论(0编辑  收藏  举报

导航