You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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;
}
}
}