gpt4 book ai didi

c# - 使用 BouncyCaSTLe 解密 Rijndael 256 block 大小

转载 作者:行者123 更新时间:2023-11-30 15:52:54 25 4
gpt4 key购买 nike

我们有一个用于加密的辅助类,老实说,它可能是多年前从 Stack Overflow 复制而来的。

目前我们正在尝试将部分代码移植到 .NET Core,但我们发现它不起作用,因为 RijndaelManaged 的 .NET Core 实现不支持 256 block 大小。从我读过的内容来看,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 的 Decrypt 方法:

    /// <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)

关于c# - 使用 BouncyCaSTLe 解密 Rijndael 256 block 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53559476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com