Search code examples
c#node.jsaesmd5cryptojs

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:

  • crypto.createCipheriv() definitely looks like the way to go, but the I don't believe the c# methods (SHA256.Create() & MD5.Create()) care for the length of the key and iv - but crypto.createCipheriv() does.

  • The c# uses a CryptoStream: So I think some kind of Buffer is in order looking at some similar C# -> Node crypto stuff

Would really appreciate some help!


Solution

  • .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);