brix / crypto-js

JavaScript library of crypto standards.
Other
15.88k stars 2.39k forks source link

Help with C# data decryption #396

Open damms005 opened 2 years ago

damms005 commented 2 years ago

I have the code below in my C# code. I am migrating same to NodeJS and handling cryptography with Crypto JS (I figured this will be my easiest option, as I have no expertise in cryptography). I need help with how to convert the C# decyption code below to Crypo JS: (I can provide the encryption code too if required)


public string SSFile_Reader( string fileToDecrypt )
{
  DESCryptoServiceProvider provider = new DESCryptoServiceProvider
  {
    Key = Encoding.UTF8.GetBytes( "13^07v90" ),
    IV = Encoding.UTF8.GetBytes( "13^07v90" ),
    Padding = PaddingMode.PKCS7
  };

  using( FileStream streamToDecrypt = new FileStream( fileToDecrypt, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ) )
  {
    ICryptoTransform cryptoTransform = provider.CreateDecryptor();
    string outputString = "";

    using( CryptoStream stream2 = new CryptoStream( streamToDecrypt, cryptoTransform, CryptoStreamMode.Read ) )
    {
      try
      {
        using( StreamReader reader = new StreamReader( stream2 ) )
        {
          try
          {
            outputString = reader.ReadToEnd();
          }
          catch
          {
           //handle error here
          }
          stream2.Close();
          streamToDecrypt.Close();

          return outputString;
        }
      }
      catch( Exception exception )
      {
        //handle error here
      }
    }
  }

  return '';
}
damms005 commented 2 years ago

I have tried the code below, but the output is just some random stuff rather than the original encrypted string:

const fs = require('fs');
const { Readable } = require("stream")
const { exit } = require('process');
const CryptoJS = require("crypto-js");

const key = '13^07v90';
const iv = '13^07v90';

const [, , pathToEncryptedFile] = process.argv;

if (!pathToEncryptedFile) {
    console.log('No file to decrypt')
    exit()
}

const encryptedString = fs.readFileSync(pathToEncryptedFile).toString();

let decryptedData = CryptoJS.DES.decrypt(fs.readFileSync(pathToEncryptedFile).toString(), key, {
    iv,
    padding: CryptoJS.pad.Pkcs7
})

console.log('decrypted data: ', decryptedData.toString())