how can i pass c encrypt code to typescript?

The C# code first generates a Sha256 hash from the password. This hash in turn is used as a password to derive a 32 bytes key and a (16 bytes) IV with PBKDF2. Other parameters for PBKDF2 are SHA1, a static salt and an iterations count of 1000.
For encryption AES-256 in CBC mode with PKCS7 padding is used. The ciphertext is returned Base64 encoded.

The posted CryptoJS code lacks the PBKDF2 and encryption part. A possible full implementation is:

function encryptdata(plaintext, password) {

  var hash = CryptoJS.SHA256(password);
  var salt = CryptoJS.lib.WordArray.create([0x01020304, 0x05060708]);

  var keyiv = CryptoJS.PBKDF2(hash, salt, {
      keySize: (256 + 128) / 32,
      iterations: 1000

  var key = CryptoJS.lib.WordArray.create(keyiv.words.slice(0, 8));
  var iv = CryptoJS.lib.WordArray.create(keyiv.words.slice(8, 12));

  var ciphertext = CryptoJS.AES.encrypt(plaintext, key, {iv:iv});
  return ciphertext.toString();

var message = "The quick brown fox jumps over the lazy dog";
var password = "A test password";
var ciphertextB64 = encryptdata(message, password); 
console.log(ciphertextB64);// Wj0aG/JQU0V4ZZLGBy++TS6gjrdMSnTyZShqAhi69kie40bfg5XMVfS+/3RCLBAT
<script src=""></script>

The C# code provides an identical ciphertext for the same plaintext and key.

Note that a static salt and a too small iterations count are insecure, s. e.g. RFC8018, sections 4.1 and 4.2 and here.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top