Skip to content Skip to sidebar Skip to footer

Reproduce Aes Decryption Method From C# In Javascript

I am trying to reproduce the following C# decryption method in JavaScript. This method is used to decrypt short strings: names, addresses, email addresses, etc. It feels tantalisin

Solution 1:

Thanks to kelalaka I managed to figure this out!

This was the code I ended up with.

import atob from 'atob';
import forge from 'node-forge';

constInitVector= [0x00, ...];
constEncryptionKey='Some Encryption Key';

constinitKey= Buffer.from(InitVector).toString(); // Changed this to `initKey`constconvertBase64StringToUint8Array= input => {
  constdata= atob(input);
  constarray= Uint8Array.from(data, b => b.charCodeAt(0));

  return array;
};

constdecrypt= cipher => {
  constcipherArray= convertBase64StringToUint8Array(cipher);

  constkey= forge.pkcs5.pbkdf2(EncryptionKey, iv, 1000, 32);

  /**
   * Added the following
   * Note the key size = 48
   *  This was due to the fact that the C# dictated that
   *  the IV was 16 bytes, starting at the end of the key.
   */constkeyAndIV= forge.pkcs5.pbkdf2(encryptionKey, initKey, 1000, 32 + 16);

  /**
   * Therefore, we cut the iv from the new string
   */constiv= keyAndIV.slice(32, 32 + 16); // 16 bytesconstdecipher= forge.cipher.createDecipher(
    'AES-CBC',
    forge.util.createBuffer(key)
  );

  decipher.start({ iv });

  decipher.update(forge.util.createBuffer(cipherArray, 'raw'));

  constresult= decipher.finish();

  if (result) {
    return decipher.output.data;
  } else {
    returnfalse;
  }
};

Post a Comment for "Reproduce Aes Decryption Method From C# In Javascript"