用C#加密。需要在NodeJS中解密

时间:2019-03-14 20:13:23

标签: javascript c# node.js encryption rijndaelmanaged

我对C#几乎一无所知。我有一种情况,其中我在c#中具有加密和解密,如下所示。但是,我想在NodeJS中实现相同的解密。谁能帮我解决这个问题。

这是盐和秘密钥匙

private static byte[] _salt = Encoding.ASCII.GetBytes("SampleSaltHere");
private string secret = "SecretHere";

加密部分

public string Encrypt(string plainText)
{
    string outStr = null;
    Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(secret, _salt);
    RijndaelManaged  aesAlg = new RijndaelManaged();

    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

    using (MemoryStream msEncrypt = new MemoryStream())
    {
        msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
        msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        {
            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
            {
                swEncrypt.Write(plainText);
            }
        }
        outStr = Convert.ToBase64String(msEncrypt.ToArray());
    }
    return outStr;
}

我要在NodeJS中实现的解密部分。

public string Decrypt(string cipherText)
{
    string plaintext = null;
    Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(secret, _salt);
    byte[] bytes = Convert.FromBase64String(cipherText);

    using (MemoryStream msDecrypt = new MemoryStream(bytes))
    {
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
        aesAlg.IV = ReadByteArray(msDecrypt);

        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
            plaintext = srDecrypt.ReadToEnd();
        }
    }
    return plaintext;
}

private static byte[] ReadByteArray(Stream s)
{
    byte[] rawLength = new byte[sizeof(int)];
    byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];

    return buffer;
}

我们非常感谢您的帮助。谢谢。

0 个答案:

没有答案