|
|
using System;
|
|
|
using System.Collections.Generic;
|
|
|
using System.IO;
|
|
|
using System.Linq;
|
|
|
using System.Security.Cryptography;
|
|
|
using System.Text;
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
namespace Module.Socket.Tool
|
|
|
{
|
|
|
/// <summary>
|
|
|
/// AES加密
|
|
|
/// </summary>
|
|
|
public class AesEncryption
|
|
|
{
|
|
|
private static readonly byte[] Key = Encoding.UTF8.GetBytes("YourSecretKeyHere12345678"); // 必须是32字节(256位)
|
|
|
private static readonly byte[] Iv = Encoding.UTF8.GetBytes("YourInitializationVectorHere"); // 必须是16字节(128位)
|
|
|
|
|
|
public static byte[] EncryptStringToBytes(string plainText)
|
|
|
{
|
|
|
if (plainText == null || plainText.Length <= 0)
|
|
|
throw new ArgumentNullException(nameof(plainText));
|
|
|
if (Key == null || Key.Length != 32)
|
|
|
throw new ArgumentNullException(nameof(Key));
|
|
|
if (Iv == null || Iv.Length != 16)
|
|
|
throw new ArgumentNullException(nameof(Iv));
|
|
|
|
|
|
byte[] encrypted;
|
|
|
|
|
|
using (Aes aesAlg = Aes.Create())
|
|
|
{
|
|
|
aesAlg.Key = Key;
|
|
|
aesAlg.IV = 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))
|
|
|
{
|
|
|
swEncrypt.Write(plainText);
|
|
|
}
|
|
|
encrypted = msEncrypt.ToArray();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return encrypted;
|
|
|
}
|
|
|
|
|
|
public static string DecryptBytesToString(byte[] cipherText)
|
|
|
{
|
|
|
if (cipherText == null || cipherText.Length <= 0)
|
|
|
throw new ArgumentNullException(nameof(cipherText));
|
|
|
if (Key == null || Key.Length != 32)
|
|
|
throw new ArgumentNullException(nameof(Key));
|
|
|
if (Iv == null || Iv.Length != 16)
|
|
|
throw new ArgumentNullException(nameof(Iv));
|
|
|
|
|
|
string plaintext = null;
|
|
|
|
|
|
using (Aes aesAlg = Aes.Create())
|
|
|
{
|
|
|
aesAlg.Key = Key;
|
|
|
aesAlg.IV = 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))
|
|
|
{
|
|
|
plaintext = srDecrypt.ReadToEnd();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return plaintext;
|
|
|
}
|
|
|
}
|
|
|
}
|