CBC 128位模式的加密块大小



我需要在128位中使用AES和CBC加密字符串

为此,我需要将块大小设置为什么?

var iv = "0000000000000000000000000000000000000000000000000000000000000000".ToByteArray();
using (Aes myAes = Aes.Create())
{
myAes.Mode = CipherMode.CBC;
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes_Aes(xml, myAes.Key, iv);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, iv);
//Display the original data and the decrypted data.
Console.WriteLine("Original:   {0}", xml);
Console.WriteLine("Round Trip: {0}", roundtrip);
}

奇怪的是,我的规格似乎不适合IV

我还没有告诉对方IV是什么,所以我想我必须使用一个0的字符串,我认为它有64个字符长,所以我使用了以上的代码

有人能帮忙吗?

暂时抛开发送密钥/IV值或将其初始化为静态值所带来的任何和所有安全概念。。。

您的代码似乎来自Microsoft的AES文档,那么为什么不坚持使用生成的IV值呢?

如果你绝对想自己设置IV(颤抖(,你需要将其设置为128位值或16字节。我不知道你的String.ToByteArray()代码到底做了什么,但如果我冒险猜测,它可能会使用UTF8或ASCII等编码将字符串转换为字节。无论哪种情况,IV数组的长度都将远远超过16字节。只需使用类似byte[] iv = new byte[16];的东西,它将默认将所有插槽初始化为0。

然而,既然你提到了,我强烈建议你仔细检查密钥/IV是如何生成或传递给另一方的。

IV不是密钥。IV代表初始化矢量https://en.wikipedia.org/wiki/Initialization_vector.要生成IV,您可以使用:https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aescryptoserviceprovider.generateiv?view=net-5.0

但是您的代码已经生成了IV和KEY。您的代码生成一个256位的密钥,而您想要一个128位的密钥。你可以通过添加来实现这一点

紧接在CCD_ 4之后的CCD_。

因此,应用于您可能开始的示例:

string original = "Here is some data to encrypt!";
// Create a new instance of the Aes
// class.  This generates a new key and initialization
// vector (IV).
using (Aes myAes = Aes.Create())
{
myAes.KeySize = 128; //After this line key size will go to 16 bytes.
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original:   {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}

最新更新