【发布时间】:2010-11-06 13:53:45
【问题描述】:
我在这里使用 AES 方法:http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
我想要一个字符串值,我将其转换为字节数组并将其传递给 AES 加密方法。字符串应该包含多少个字符才能产生方法期望的正确字节数组大小?
static byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the stream used to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt = null;
// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged aesAlg = null;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return msEncrypt.ToArray();
}
【问题讨论】:
-
在您的示例中,字符串是“您要加密的内容”。它与“AES 方法所期望的”无关。对称算法需要字节数组、一个密钥和一个初始值,才能开始加密/解密。您将这些作为参数传递给您自己的方法,并将它们直接传递给算法构造函数。因此,您的示例中的字符串可以是任意长度。您可能关心的是如何获得正确大小的密钥和 iv 字节数组,这取决于算法。在 SwDevMan81 的回答中,您可以看到他在您的方法之前初始化了 key+iv。
标签: c# asp.net encryption aes rijndaelmanaged