英文:
Conversion from buffer to string gives different results in c# and Nodejs
问题
Here is the translated code snippet:
const crypto = require('crypto')
const str = '34924979';
const sha = crypto.createHash('sha512').update(str).digest('utf8');
const hash = sha.toString('utf-8').replace(/\uFFFD/g, '?');
console.log(hash);
This code is the Node.js equivalent of the C# code you provided for converting a string to a SHA-512 hash and handling the output as a string.
英文:
I'm trying to convert this function from C# to node but I'm getting different results when I try to convert a buffer to a string.
string str = "34924979";
System.Security.Cryptography.SHA512 sha = new System.Security.Cryptography.SHA512Managed();
byte[] ba = System.Text.Encoding.ASCII.GetBytes(str);
byte[] data= sha.ComputeHash(ba);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(data));
>> `?????gV)????∟?Z?s??v$We-??N?"?w????0??\i♠G???
that's what i'm trying to do.
const crypto = require('crypto')
const str = '34924979';
const sha = crypto.createHash('sha512').update(str).digest('utf8');
const hash = sha.toString('utf-8').replace(/\uFFFD/g, '?');
console.log(hash);
>> `????gV)????∟?Z?v$We-??N?"?w????0?\i♠Gߕ?
答案1
得分: 2
你在C#和JS中使用了不同的编码。
尝试将JS代码更改为以下内容:
const sha = crypto.createHash('sha512').update(str).digest('ascii');
const hash = sha.toString('ascii');
英文:
You're using different encodings in C# and JS.
Try changing the JS code to the following:
const sha = crypto.createHash('sha512').update(str).digest('ascii');
const hash = sha.toString('ascii');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论