[英]Matching Node.js aes-128-ecb (hex) encryption with C# .NET Core 3.1
I'm using an external API which expect the request body encrypted with aes-128-ecb (hex).我正在使用一个外部 API,它期望使用 aes-128-ecb(十六进制)加密的请求正文。 I got it to work with JavaScript using Node.js with the following code (same key is used per session, but that's not the problem here):
我使用 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');
I want now to also do some requests from my C# .NET Core 3.1.我现在还想从我的 C# .NET Core 3.1 做一些请求。 application, but no matter what I try, I do not get the same result.
应用程序,但无论我尝试什么,我都没有得到相同的结果。 The API is not accepting my request as well.
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();
And FetchList Class:和 FetchList 类:
public class FetchList
{
public string fetch_list { get; set; }
}
Thanks to @Topaco I was able to solfe my problem.感谢@Topaco,我能够解决我的问题。 here is how the code now looks like:
下面是代码现在的样子:
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.