C# 使用BouncyCastle解密Rijndael 256块大小

C# 使用BouncyCastle解密Rijndael 256块大小,c#,bouncycastle,encryption-symmetric,C#,Bouncycastle,Encryption Symmetric,我们有一个用于加密的助手类,老实说,它可能是多年前从堆栈溢出复制的 目前,我们正在尝试将部分代码移植到.NET Core,但我们发现它不起作用,因为RijndaelManaged的.NET Core实现不支持256块大小。据我所知,BouncyCastle似乎仍然应该支持它,但我无法让它工作。“未加密”的文本只是一堆胡言乱语。我肯定我做错了什么,但就我个人而言,我无法理解这一点 以下是该类的原始.Net Framework版本: internal static class StringEncry

我们有一个用于加密的助手类,老实说,它可能是多年前从堆栈溢出复制的

目前,我们正在尝试将部分代码移植到.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;
    }
}
下面是我尝试使用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;
        }
    }
}
//
///解密字符串
/// 
/// 
/// 
公共静态字符串解密(字符串密文)
{
if(密文==null)
{
抛出新ArgumentNullException(nameof(cipherText));
}
//获取表示以下内容的完整字节流:
//[32字节的Salt]+[32字节的IV]+[n字节的密文]
var ciphertextbyteswithaltandiv=WebEncoders.Base64UrlDecode(密文);
//通过从提供的密文字节中提取前32个字节来获取saltbytes。
var saltStringBytes=CipherTextBytes和altandiv.Take(Keysize/8.ToArray();
//通过从提供的密文字节中提取接下来的32个字节来获取IV字节。
var ivStringBytes=ciphertextbytes with altandiv.Skip(Keysize/8).Take(Keysize/8).ToArray();
//通过从密文字符串中删除前64个字节来获取实际的密文字节。
var cipherTextBytes=cipherTextBytes with saltandiv.Skip((Keysize/8)*2)。Take(cipherTextBytes with saltandiv.Length-((Keysize/8)*2)).ToArray();
使用(var password=new Rfc2898DeriveBytes(superSecretPassPhrase,saltStringBytes,_迭代))
{
var keyBytes=password.GetBytes(Keysize/8);
var发动机=新RijndaelEngine(256);
var blockCipher=新的CBlockcipher(引擎);
var cipher=new PaddedBufferedBlockCipher(blockCipher,new Pkcs7Padding());
var keyParam=新的KeyParameter(keyBytes);
var keyParamWithIV=新参数swithiv(keyParam,ivStringBytes,0,32);
cipher.Init(true,keyParamWithIV);
var outputBytes=新字节[cipher.GetOutputSize(cipherTextBytes.Length)];
var length=cipher.ProcessBytes(cipherTextBytes,outputBytes,0);
var finalBytes=cipher.DoFinal(输出字节,0,长度);
var final=Encoding.UTF8.GetString(最终字节);
返回最终结果;
}
}
}

提前谢谢!我肯定我在做一些愚蠢的事情,但我不是密码专家,我很难找到好的BouncyCastle示例。

我相信你的问题就在眼前

cipher.Init(true,keyParamWithIV)

第一个参数初始化加密(如果为true)和解密(如果为false)。如果将其设置为false,它应该可以工作


请定义“无法使其工作”的含义。哦,是的,这是一种重要的信息,对吗?编辑了我的问题,包括输出文本是一堆乱七八糟的东西,而不是预期的字符串。谢谢你的发帖,真的救了我一天!您是否也使用BouncyCastle实现了加密?提前谢谢!谢谢那绝对是我错过的最重要的一块!