63 lines
2.0 KiB
C#
63 lines
2.0 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
public class Cryptography
|
|
{
|
|
public static string EncryptString(string plainText, string key, string iv)
|
|
{
|
|
using (Aes aesAlg = Aes.Create())
|
|
{
|
|
aesAlg.Key = GetKeyBytes(key, aesAlg.KeySize / 8);
|
|
aesAlg.IV = GetKeyBytes(iv, 16);
|
|
|
|
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
|
|
|
|
using (MemoryStream msEncrypt = new MemoryStream())
|
|
{
|
|
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
|
|
{
|
|
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
|
|
csEncrypt.Write(plainBytes, 0, plainBytes.Length);
|
|
csEncrypt.FlushFinalBlock();
|
|
}
|
|
return Convert.ToBase64String(msEncrypt.ToArray());
|
|
}
|
|
}
|
|
}
|
|
|
|
public static string DecryptString(string cipherText, string key, string iv)
|
|
{
|
|
byte[] cipherBytes = Convert.FromBase64String(cipherText);
|
|
using (Aes aesAlg = Aes.Create())
|
|
{
|
|
aesAlg.Key = GetKeyBytes(key, aesAlg.KeySize / 8);
|
|
aesAlg.IV = GetKeyBytes(iv, 16);
|
|
|
|
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
|
|
|
|
using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
|
|
{
|
|
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
|
|
{
|
|
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
|
|
{
|
|
return srDecrypt.ReadToEnd();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static byte[] GetKeyBytes(string key, int keySize)
|
|
{
|
|
|
|
|
|
using (var deriveBytes = new PasswordDeriveBytes(key, null))
|
|
{
|
|
return deriveBytes.GetBytes(keySize);
|
|
}
|
|
}
|
|
}
|