标签:c asp-net encryption aes rijndaelmanaged
我在这里使用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();
}
解决方法:
纯文本的大小无关紧要.只需确保在decryptStringFromBytes_AES(byte [] cipherText,byte [] Key,byte [] IV)方法中使用完全相同的IV和Key以及加密字节.这将返回给您输入的纯文本.
例如:
string plain_text = "Cool this works";
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
byte[] key = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
byte[] encrytped_text = encryptStringToBytes_AES(plain_text, key, iv);
string plain_text_again = decryptStringFromBytes_AES(encrypted_text, key, iv);
在这里你应该看到纯文本和纯文本再次相同.现在继续将plain_text更改为你想要的任何东西,看看这个工作正常.
RijndaelManaged的默认值为:
BlockSize:128
KeySize:256
模式:CipherMode.CBC
填充:PaddingMode.PKCS7
有效的IV大小是:
128,192,256位(这是BlockSize,请确保将其设置为您正在使用的大小IV)
有效密钥大小为:
128,192,256位(这是KeySize,请确保将其设置为您正在使用的大小键)
这意味着byte [] iv可以是16,24或32个字节(在我上面的例子中是16个字节),而byte []键也可以是16,24或32个字节(在我上面的例子中它是16个字节) ).
希望有所帮助.
标签:c,asp-net,encryption,aes,rijndaelmanaged 来源: https://codeday.me/bug/20190607/1192722.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。