如何将 C# 加密代码传递给 TypeScript?

How can I pass C# encrypt code to TypeScript?

我有 C# 代码,但我需要传入 TypeScript。在 C# 中,我使用这个库 using System.Security.Cryptography;,在 TypeScript 中,我使用这个库 var CryptoJS = require("crypto-js")。我有代码的第一部分(SHA256加密)但我需要第二部分(Aes加密)。

这是 C# 代码:

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;
    }

并且是我的打字稿代码,函数encryptdata()与C#中的第一个encryptdata()相同。结果是一样的。

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);
 }

感谢您的帮助。

C# 代码首先从密码生成 Sha256 哈希。该散列又用作密码,以使用 PBKDF2 派生 32 字节密钥和(16 字节)IV。 PBKDF2 的其他参数是 SHA1、静态盐和 1000 次迭代计数。
对于加密,使用 CBC 模式的 AES-256 和 PKCS7 填充。密文返回Base64编码。

发布的 CryptoJS 代码缺少 PBKDF2 和加密部分。一个可能的完整实现是:

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>

C# 代码为相同的明文和密钥提供相同的密文。

请注意,静态盐和太小的迭代次数是不安全的,s。例如RFC8018, sections 4.1 and 4.2 and here.