【发布时间】:2021-10-18 15:30:56
【问题描述】:
我有这个 c# 代码:
public string Encrypt( string aesKey)
{
var data = "ASD_POC";
var aesKey = "OxLDVPTHLk5EHR5AE8O0rg==";
var token = Encoding.UTF8.GetBytes(data);
byte[] _key = Convert.FromBase64String(aesKey);
string retnResult = string.Empty;
AesCryptoServiceProvider aesProvider = new System.Security.Cryptography.AesCryptoServiceProvider();
MemoryStream memStream = null;
CryptoStream cryptoStream = null;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
byte[] cipherText;
try
{
aesProvider.Mode = CipherMode.CBC;
aesProvider.Padding = PaddingMode.PKCS7;
aesProvider.BlockSize = 128;
aesProvider.KeySize = 128;
aesProvider.GenerateIV();
memStream = new MemoryStream();
cryptoStream = new CryptoStream(memStream, aesProvider.CreateEncryptor(_key, aesProvider.IV), CryptoStreamMode.Write);
cryptoStream.Write(token, 0, token.Length);
cryptoStream.FlushFinalBlock();
cipherText = memStream.ToArray();
var combinedIvCipherText = new byte[aesProvider.IV.Length + cipherText.Length];
Array.Copy(aesProvider.IV, 0, combinedIvCipherText, 0, aesProvider.IV.Length);
Array.Copy(cipherText, 0, combinedIvCipherText, aesProvider.IV.Length, cipherText.Length);
retnResult = Convert.ToBase64String(combinedIvCipherText);
}
我已尝试为 Postman 集合实现此功能:
var CryptoJS = require("crypto-js");
// Generate random 16 bytes to use as IV
var IV = CryptoJS.lib.WordArray.random(16);
var data = "ASD_POC";
var aesKey = "OxLDVPTHLk5EHR5AE8O0rg==";
var tokenData = atob(aesKey);
var Key = Uint8Array.from(tokenData, b => b.charCodeAt(0));
function encrypt(data) {
var val = CryptoJS.enc.Utf8.parse(data);
var encrypted = CryptoJS.AES.encrypt(
val,
Key,
{
iv: IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
keySize: 128,
BlockSize: 128
}).toString();
console.log(encrypted);
var b64 = CryptoJS.enc.Base64.parse(encrypted).toString(CryptoJS.enc.Hex);
console.log(b64)
return b64;
}
但是,当我尝试从 CryptoJs 串入字符串时 - 我遇到了一个我不能的错误。 我在实施中做错了什么?我尝试在 Google 上搜索更多关于 CryptoJs 的信息 - 但找不到更多 than 并且它不包含很多信息。
【问题讨论】:
标签: encryption postman aes cryptojs