简体   繁体   中英

How can I pass C# encrypt code to TypeScript?

I have code in C# but I need to pass in TypeScript. In C# I use this library using System.Security.Cryptography; and in TypeScript I use this library var CryptoJS = require("crypto-js") . I have the first part of the code (SHA256 encryptation) but I need the second part(Aes encryptation).

This is the C# Code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 //now i have pass this function in typescript and the result is the same
 public string Encrypt(string plainText, string password)
    {
       
        var bytesToBeEncrypted = Encoding.UTF8.GetBytes(plainText);
        var passwordBytes = Encoding.UTF8.GetBytes(password);

        // Hash the password with SHA256
        passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

        var bytesEncrypted = SecurityEncrypt.Encrypt(bytesToBeEncrypted, passwordBytes);

        return Convert.ToBase64String(bytesEncrypted);
    }
   //i need pass this function in typescript
  private static byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        byte[] encryptedBytes = null;

        // Set your salt here, change it to meet your flavor:
        // The salt bytes must be at least 8 bytes.
        var saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);

                AES.KeySize = 256;
                AES.BlockSize = 128;
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = key.GetBytes(AES.BlockSize / 8);

                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                    cs.Close();
                }

                encryptedBytes = ms.ToArray();
            }
        }

        return encryptedBytes;
    }

And is my typescript code, the function encryptdata() is the same that the first encryptdata() in C#. And the result is the same.

encryptdata(){
var CryptoJS = require("crypto-js");

let messageutf=CryptoJS.enc.Utf8.parse(this.message);
let encryputf=CryptoJS.enc.Utf8.parse(this.encryptKey);
var hashpassword=CryptoJS.SHA256(encryputf);
var hash = CryptoJS.SHA256(messageutf, hashpassword);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return this._makeqr.makeQr(hashInBase64);
 }

Thanks for your help.

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="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></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, seg RFC8018 , sections 4.1 and 4.2 and here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM