鉴于我将KeySize设置为192,当我通过执行以下操作加密某些数据时:
static void Main()
{
var querystrings = "dataToEncrypt";
byte[] keyvalue = new byte[] { 241, 205, 121, 123, 109, 246, 247, 103, 31, 225, 167, 220, 247, 119, 247, 119, 78, 125, 127, 167, 156, 213, 230, 250, };
byte[] ivvalue = new byte[] { 194, 177, 79, 213, 87, 46, 213, 189, 243, 169, 32, 13, 217, 62, 34, 170, };
byte[] querystringBytes = Encoding.UTF8.GetBytes(querystrings);
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.BlockSize = 128;
rijndaelManaged.KeySize = 192;
rijndaelManaged.IV = ivvalue;
rijndaelManaged.Key = keyvalue;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.Mode = CipherMode.CBC;
using (MemoryStream memoryStream = new MemoryStream())
{
ICryptoTransform transform = rijndaelManaged.CreateEncryptor();
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
{
cryptoStream.Write(querystringBytes, 0, querystringBytes.Length);
cryptoStream.FlushFinalBlock();
var output = Convert.ToBase64String(memoryStream.ToArray());
Console.WriteLine($"{output}");
Console.ReadKey();
}
}
}
}
数据加密,因为IV和加密密钥分别为128位和192位长。但是,如果我将加密密钥设置为128位长(为了参数,我们使用与IV相同的字节数组),即
static void Main()
{
var querystrings = "dataToEncrypt";
byte[] keyvalue = new byte[] { 194, 177, 79, 213, 87, 46, 213, 189, 243, 169, 32, 13, 217, 62, 34, 170, };
byte[] ivvalue = new byte[] { 194, 177, 79, 213, 87, 46, 213, 189, 243, 169, 32, 13, 217, 62, 34, 170, };
byte[] querystringBytes = Encoding.UTF8.GetBytes(querystrings);
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.BlockSize = 128;
rijndaelManaged.KeySize = 192;
rijndaelManaged.IV = ivvalue;
rijndaelManaged.Key = keyvalue;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.Mode = CipherMode.CBC;
using (MemoryStream memoryStream = new MemoryStream())
{
ICryptoTransform transform = rijndaelManaged.CreateEncryptor();
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
{
cryptoStream.Write(querystringBytes, 0, querystringBytes.Length);
cryptoStream.FlushFinalBlock();
var output = Convert.ToBase64String(memoryStream.ToArray());
Console.WriteLine($"{output}");
Console.ReadKey();
}
}
}
}
这仍然会毫无例外地加密。我的问题是:
当我明确将KeySize设置为192时,KeySize在内部做了什么,因为它接受128位加密密钥?为什么没有例外?
答案 0 :(得分:4)
RijndaelManaged类的Key和KeySize属性继承自基类SymmetricAlgorithm类。 MSDN Library中没有详细记录这些属性的精确行为,但是如果查看SymmetricAlgorithm source code,您将看到Key和KeySize属性相互交互,如下所示:
因此,如果您正在设置Key属性,那么事先没有必要设置KeySize属性。