我已经得到了一些实现SHA 256散列和AES-256-cbc的c#代码。现在我必须把它们翻译成NodeJS。我在这里尝试了几个选项、文档和问题/答案,但都没有帮助。因为我是第一次使用加密,可能是编码出了问题-但不能弄清楚到底是什么问题。下面是c#实现:
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
public class HelloWorld
{
public static void Main(string[] args)
{
HelloWorld h1 = new HelloWorld();
Console.WriteLine(h1.EncryptText("Vitthal", "Vitthal"));
}
public string EncryptText(string pInput, string password)
{
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(GenerateSHA256String(pInput));
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
// method name GenerateSHA256String and code
public string GenerateSHA256String(string inputString)
{
StringBuilder stringBuilder = new StringBuilder();
try
{
SHA256 sha256 = SHA256Managed.Create();
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
byte[] hash = sha256.ComputeHash(bytes);
for (int i = 0; i <= hash.Length - 1; i++)
stringBuilder.Append(hash[i].ToString("X2"));
return stringBuilder.ToString();
}
catch (Exception ex)
{
}
return stringBuilder.ToString();
}
// method name AES_Encrypt and code
private byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
}
下面是使用加密的NodeJS实现:
const GenerateSHA256String = (object) => {
const buff = Buffer.from(object.toString());
const hash = createHash('sha256');
hash.update(buff);
const hashed = hash.digest('hex');
return hashed;
}
const getEncryptedChecksum = (object) => {
const payload = GenerateSHA256String(object);
console.log(Buffer.from(payload));
const passKey = Buffer.from('Vitthal');
const saltString = [1,2,3,4,5,6,7,8];
const key = pbkdf2Sync(GenerateSHA256String(passKey), Buffer.from(saltString), 1000, 100, 'sha1');
const encKey = key.subarray(0, 32);
const encIV = key.subarray(32, 48);
const cipher = createCipheriv('aes-256-cbc', encKey, encIV);
let encrypted = cipher.update(Buffer.from(payload), 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
}
console.log(getEncryptedChecksum('Vitthal'));
在这方面的任何帮助都是非常感谢的。
1条答案
按热度按时间gr8qqesn1#
终于解决了。这是编码问题。一些奇怪的行为不同的c#和nodejs。无论如何,这是最终的nodejs代码的工作!