[英]Matching Node.js aes-128-ecb (hex) encryption with C# .NET Core 3.1
我正在使用一個外部 API,它期望使用 aes-128-ecb(十六進制)加密的請求正文。 我使用 Node.js 和以下代碼讓它與 JavaScript 一起工作(每個會話使用相同的鍵,但這不是這里的問題):
var crypto = require('crypto'),
algorithm = 'aes-128-ecb',
key = 'E572F45E8D79CAF92B4BD3B375820831';
var fetchlist = {
fetch_list: '[{"name":"itemInfo","controller":"catalog.BLCCatalogItem","method":"getDetailWithColor","params":[264,86]}]',
};
var message = JSON.stringify(fetchlist);
var cipher = crypto.createCipher(algorithm, key);
var crypted = cipher.update(message, 'utf8', 'hex');
crypted += cipher.final('hex');
我現在還想從我的 C# .NET Core 3.1 做一些請求。 應用程序,但無論我嘗試什么,我都沒有得到相同的結果。 API 也不接受我的請求。
var fetchList = new FetchList();
fetchList.fetch_list = "[{\"name\":\"itemInfo\",\"controller\":\"catalog.BLCCatalogItem\",\"method\":\"getDetailWithColor\",\"params\":[264,86]}]";
string message = JsonConvert.SerializeObject(fetchList);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Key = UTF8Encoding.UTF8.GetBytes(Key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] data = Encoding.UTF8.GetBytes(message);
ICryptoTransform encrypt = aes.CreateEncryptor();
byte[] dest = encrypt.TransformFinalBlock(data, 0, data.Length);
StringBuilder hex = new StringBuilder(dest.Length * 2);
foreach (byte b in dest)
hex.AppendFormat("{0:x2}", b);
var output = hex.ToString();
和 FetchList 類:
public class FetchList
{
public string fetch_list { get; set; }
}
感謝@Topaco,我能夠解決我的問題。 下面是代碼現在的樣子:
var key = new OpenSslCompatDeriveBytes(UTF8Encoding.UTF8.GetBytes("E572F45E8D79CAF92B4BD3B375820831"), null, "MD5", 1).GetBytes(16);
var fetchList = new FetchList();
fetchList.fetch_list = "[{\"name\":\"itemInfo\",\"controller\":\"catalog.BLCCatalogItem\",\"method\":\"getDetailWithColor\",\"params\":[137696,115]}]";
string message = JsonConvert.SerializeObject(fetchList);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Key = key;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] data = Encoding.UTF8.GetBytes(message);
ICryptoTransform encrypt = aes.CreateEncryptor();
byte[] dest = encrypt.TransformFinalBlock(data, 0, data.Length);
StringBuilder hex = new StringBuilder(dest.Length * 2);
foreach (byte b in dest)
hex.AppendFormat("{0:x2}", b);
var output = hex.ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.