簡體   English   中英

使用 BouncyCastle 解密 Rijndael 256 塊大小

[英]Decrypt Rijndael 256 Block Size with BouncyCastle

我們有一個用於加密的輔助類,老實說,它可能是幾年前從 Stack Overflow 復制而來的。

目前,我們正在嘗試將部分代碼移植到 .NET Core,但我們發現它不起作用,因為RijndaelManaged的 .NET Core 實現不支持 256 塊大小。 從我讀到的內容來看,BouncyCastle 似乎仍然應該支持它,但我無法讓它工作。 “未加密”的文本只是一堆亂碼。 我確定我做錯了什么,但對於我的生活,我無法弄清楚這一點。

這是該類的原始 .Net Framework 版本:

internal static class StringEncryptor
{
    private const int Keysize = 256;
    private const int _iterations = 1000;
    private const int _hashLenth = 20;

    public static string Encrypt(string plainText, string superSecretPassPhrase)
    {
        // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
        // so that the same Salt and IV values can be used when decrypting.  
        var saltStringBytes = Generate256BitsOfRandomEntropy();
        var ivStringBytes = Generate256BitsOfRandomEntropy();
        var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        using (var password = new Rfc2898DeriveBytes(superSecretPassPhrase, saltStringBytes, _iterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                            var cipherTextBytes = saltStringBytes;
                            cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                            cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                            memoryStream.Close();
                            cryptoStream.Close();
                            return WebEncoders.Base64UrlEncode(cipherTextBytes);
                            //return System.Web.HttpServerUtility.UrlTokenEncode(cipherTextBytes);
                        }
                    }
                }
            }
        }
    }



    public static string Decrypt(string cipherText, string superSecretPassPhrase)
    {
        if (cipherText == null)
        {
            throw new ArgumentNullException(nameof(cipherText));
        }
        // Get the complete stream of bytes that represent:
        // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
        var cipherTextBytesWithSaltAndIv = WebEncoders.Base64UrlDecode(cipherText);
        // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
        var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
        // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
        var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

        using (var password = new Rfc2898DeriveBytes(superSecretPassPhrase, saltStringBytes, _iterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
    }

    private static byte[] Generate256BitsOfRandomEntropy()
    {
        var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
        using (var rngCsp = new RNGCryptoServiceProvider())
        {
            // Fill the array with cryptographically secure random bytes.
            rngCsp.GetBytes(randomBytes);
        }
        return randomBytes;
    }
}

這是我嘗試使 Decrypt 方法與 BouncyCastle 一起使用的嘗試:

    /// <summary>
    /// Decrypt a string
    /// </summary>
    /// <param name="cipherText"></param>
    /// <returns></returns>
    public static string Decrypt(string cipherText)
    {
        if (cipherText == null)
        {
            throw new ArgumentNullException(nameof(cipherText));
        }
        // Get the complete stream of bytes that represent:
        // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
        var cipherTextBytesWithSaltAndIv = WebEncoders.Base64UrlDecode(cipherText);
        // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
        var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
        // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
        var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

        using (var password = new Rfc2898DeriveBytes(superSecretPassPhrase, saltStringBytes, _iterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            var engine = new RijndaelEngine(256);
            var blockCipher = new CbcBlockCipher(engine);
            var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
            var keyParam = new KeyParameter(keyBytes);
            var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32);
            cipher.Init(true, keyParamWithIV);
            var outputBytes = new byte[cipher.GetOutputSize(cipherTextBytes.Length)];
            var length = cipher.ProcessBytes(cipherTextBytes, outputBytes, 0);
            var finalBytes = cipher.DoFinal(outputBytes, 0, length);
            var final = Encoding.UTF8.GetString(finalBytes);
            return final;
        }
    }
}

提前致謝! 我確定我在做一些愚蠢的事情,但我不是密碼專家,而且我很難找到好的 BouncyCastle 示例。

我相信你的問題是在線的

cipher.Init(true, keyParamWithIV);

第一個參數初始化密碼,如果為真則用於加密,如果為假則用於解密。 如果你將它設置為 false 它應該可以工作。

http://people.eecs.berkeley.edu/~jonah/bc/org/bouncycastle/crypto/paddings/PaddedBufferedBlockCipher.html#init(boolean,%20org.bouncycastle.crypto.CipherParameters)

有人知道這是否曾經解決過嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM