我一直试图将HMAC中间件代码片段转换为C#。Node代码非常简单。
const hash = crypto
.createHmac('sha256', 'SHA-Key')
.update(JSON.stringify(req.body))
.digest('hex');
if (hash === req.header('X-HMAC-Sha-256')) {
next();
} else {
res.send(401, 'Not authorized.');
}我的C#代码
public string CalculateSHA256Hash(byte[] key, string requestContent, string senderHash)
{
string hexHash = "";
// Initialize the keyed hash object.
using (HMACSHA256 hmac = new HMACSHA256(key))
{
byte[] requestByteArray = Encoding.UTF8.GetBytes(requestContent);
// Create a FileStream for the source file.
using (MemoryStream inStream = new MemoryStream(requestByteArray))
{
// Read in the storedHash.
inStream.Read(requestByteArray, 0, requestByteArray.Length);
// Compute the hash of the remaining contents of the file.
// The stream is properly positioned at the beginning of the content,
// immediately after the stored hash value.
byte[] computedHash = hmac.ComputeHash(inStream);
hexHash = Convert.ToHexString(computedHash);
}
}
return hexHash;
}当我运行代码时,我永远不会得到与发送者HMAC哈希相同的结果。这是否与node.js中的Digest Hex与my convert有关?
发布于 2022-05-25 14:12:31
因此,我需要深入研究node.js代码为HMAC哈希所做的具体工作。我发现,一旦我理解了json.stringify()正在做什么,这就变得很容易实现。
public string CalculateSHA256Hash(byte[] key, string requestContent)
{
string hexHash = "";
try
{
// Initialize the keyed hash object.
using (HMACSHA256 hmac = new HMACSHA256(key))
{
byte[] requestByteArray = Encoding.UTF8.GetBytes(requestContent);
// Create a FileStream for the source request body.
using (MemoryStream inStream = new MemoryStream(requestByteArray))
{
byte[] computedHash = hmac.ComputeHash(inStream);
hexHash = Convert.ToHexString(computedHash).ToLower();
}
}
}
catch (Exception e)
{
throw;
}
return hexHash;
}我使用以下方法获得与json.stringify()等价的内容
//Stringify
strBody = strBody.Replace(" ", "");
strBody = strBody.Replace(Environment.NewLine, "");https://stackoverflow.com/questions/72290364
复制相似问题