Jan 22, 2019

Decryption function (dotnet & nodejs)

In "Encryption function (dotnet & nodejs)" post I described encryption functions.
In this post you can see decrypt functions.

Nodejs uses "crypto-js" package.
Dotnet uses "System.Security.Cryptography" namespace.

Dotnet

 

public static string Decrypt(string encryptedBase64)
{
 byte[] rawSecretKey = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };  
 string PassPhrase = "passPhrase";

 MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
 byte[] data = Encoding.ASCII.GetBytes(PassPhrase);
 data.Dump("data");
 
 byte[] passwordKey = x.ComputeHash(data);
 
 RijndaelManaged rijndael = new RijndaelManaged();
 ICryptoTransform rijndaelDecryptor = rijndael.CreateDecryptor(passwordKey, rawSecretKey);
 try
 {
  byte[] encryptedData = Convert.FromBase64String(encryptedBase64);
  byte[] newClearData = rijndaelDecryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
  return Encoding.ASCII.GetString(newClearData);
 }
 catch (Exception ex)
 {
  return null;
 }
}

Node.js

 

 var bytes = CryptoJS.AES.decrypt(encrypted, myRijndaelKey, {
        iv: ivCodeWords,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
 var plaintext = bytes.toString(CryptoJS.enc.Utf8);
 console.log("decrypted text: " + plaintext);

2 comments:

Anonymous said...

Thanks for finally writing about >"Decryption function (dotnet & nodejs)" <Loved it!

Anonymous said...

Hi there, just wanted to tell you, I loved this article.
It was inspiring. Keep on posting!