本文整理汇总了C#中System.Security.Cryptography.AesManaged.SetKey方法的典型用法代码示例。如果您正苦于以下问题:C# AesManaged.SetKey方法的具体用法?C# AesManaged.SetKey怎么用?C# AesManaged.SetKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.AesManaged
的用法示例。
在下文中一共展示了AesManaged.SetKey方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Encrypt
public static byte[] Encrypt(string text, string password, byte[] salt = null)
{
if (string.IsNullOrEmpty(text)) throw new ArgumentNullException("text");
if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");
if (salt == null) salt = DefaultSalt;
var aes = new AesManaged();
byte[] encryptedData;
try
{
aes.SetKey(password, salt);
var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (var ms = new MemoryStream())
{
ms.Write(BitConverter.GetBytes(aes.IV.Length), 0, sizeof(int));
ms.Write(aes.IV, 0, aes.IV.Length);
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs))
sw.Write(text);
encryptedData = ms.ToArray();
}
}
finally
{
aes.Clear();
}
return encryptedData;
}
示例2: Decrypt
public static string Decrypt(byte[] encryptedData, string password, byte[] salt = null)
{
if (encryptedData == null) throw new ArgumentNullException("encryptedData");
if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");
if (salt == null) salt = DefaultSalt;
var aes = new AesManaged();
string text;
try
{
aes.SetKey(password, salt);
using (var ms = new MemoryStream(encryptedData))
{
aes.IV = ms.GetIV();
var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var sr = new StreamReader(cs))
text = sr.ReadToEnd();
}
}
finally
{
aes.Clear();
}
return text;
}