/// <summary>
/// 加密
/// </summary>
/// <param name="plainText">需要加密的字符串</param>
/// <returns></returns>
public static string EncryptString(string plainText)
{
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("IV");
byte[] encrypted;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.ASCII.GetBytes(Key);
aesAlg.IV = Encoding.ASCII.GetBytes(IV);
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt, Encoding.UTF8))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="cipherStr">需要解密的字符串</param>
/// <returns></returns>
public static string DecryptString(string cipherStr)
{
var cipherText = Convert.FromBase64String(cipherStr);
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
string plaintext = null;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.ASCII.GetBytes(Key);
aesAlg.IV = Encoding.ASCII.GetBytes(IV);
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt, Encoding.UTF8))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
unity C# 中关于字符串加密
最新推荐文章于 2024-05-10 09:41:49 发布