Harry Lincoln
Harry Lincoln

Reputation: 656

C# to node crypto hashing - md5 and sha256

Here is the C# code I'm trying to port into Node crypto, but since I don't know c# it's proving a little tricky!

public static string EncryptStringToBytes_Aes(string username, string password) 
    {
      string encrypted = string.Empty;
      byte[] clearBytes = Encoding.UTF8.GetBytes(password);
      Console.WriteLine("1." + clearBytes);
      using (Aes aesAlg = Aes.Create())
      {
        byte[] k; byte[] iv;
        byte[] bytes = Encoding.UTF8.GetBytes(username); 
        k = SHA256.Create().ComputeHash(bytes);
        iv = MD5.Create().ComputeHash(bytes);
        aesAlg.Key = k;
        aesAlg.IV = iv;
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        using (MemoryStream msEncrypt = new MemoryStream()) 
        {
          using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
          csEncrypt.Write(clearBytes, 0, clearBytes.Length); }
          encrypted = Convert.ToBase64String(msEncrypt.ToArray()); 
        }
      }
      return encrypted;
    }

C# repl:

https://repl.it/@HarryLincoln/NegligiblePoisedHexagon

Node workings:

Would really appreciate some help!

Upvotes: 0

Views: 677

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

.Net Framework - AES encryption uses a 256 bit key and CBC mode and PKCS7 padding by default.

The code to port is very simple to read, it just does this:

return

BASE64 (
    AES_ENCRYPT (
        password,
        Key: SHA256(username),
        IV: MD5(username)
   )
)

The same can easily be achieved on Node.

const crypto = require('crypto');

const key = crypto.createHash('sha256').update('username', 'utf8').digest();
const iv = crypto.createHash('md5').update('username', 'utf8').digest();

const encryptor = crypto.createCipheriv("aes-256-cbc", key, iv);

var crypted = Buffer.concat([encryptor.update('password', 'utf8'), encryptor.final()]);

let base64data = crypted.toString('base64');

console.log(base64data);

Upvotes: 1

Related Questions