0

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!

Harry Lincoln
  • 614
  • 2
  • 9
  • 30
  • 2
    `SHA256` and `MD5` don't care about the length of the data that you're hashing, but `AES` certainly cares about the length of the key and the iv. A SHA256 hash of the user name comes out to 32 bytes, or 256 bits. A MD5 hash of the user name comes out to 16 bytes, or 128 bits. Both are sizes that `AES` supports. So, I don't know much about `crypto` from node, but I imagine that if you're hashing the user name the same way to get the key and iv you could provide them to `crypto.createCipheriv` – Joshua Robinson Mar 31 '20 at 13:56

1 Answers1

1

.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);
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26