54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO.Compression;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace YuanXuan.IM.Common.Helpers
|
|
{
|
|
public static class AesEncryptHelper
|
|
{
|
|
static string key = "ThisIsAVerySecre";
|
|
static string iv = "16ByteIV12345678";
|
|
|
|
// 使用CBC模式加密并返回Base64字符串
|
|
public static string EncryptToShortString(string plainText)
|
|
{
|
|
using (Aes aesAlg = Aes.Create())
|
|
{
|
|
aesAlg.Key = Encoding.UTF8.GetBytes(key);
|
|
aesAlg.IV = Encoding.UTF8.GetBytes(iv);
|
|
aesAlg.Mode = CipherMode.CBC;
|
|
aesAlg.Padding = PaddingMode.PKCS7;
|
|
|
|
ICryptoTransform encryptor = aesAlg.CreateEncryptor();
|
|
byte[] encryptedBytes = encryptor.TransformFinalBlock(
|
|
Encoding.UTF8.GetBytes(plainText), 0, plainText.Length);
|
|
|
|
return Convert.ToBase64String(encryptedBytes);
|
|
}
|
|
}
|
|
|
|
// 解密Base64加密字符串
|
|
public static string DecryptFromShortString(string cipherText)
|
|
{
|
|
using (Aes aesAlg = Aes.Create())
|
|
{
|
|
aesAlg.Key = Encoding.UTF8.GetBytes(key);
|
|
aesAlg.IV = Encoding.UTF8.GetBytes(iv);
|
|
aesAlg.Mode = CipherMode.CBC;
|
|
aesAlg.Padding = PaddingMode.PKCS7;
|
|
|
|
ICryptoTransform decryptor = aesAlg.CreateDecryptor();
|
|
byte[] cipherBytes = Convert.FromBase64String(cipherText);
|
|
byte[] decryptedBytes = decryptor.TransformFinalBlock(
|
|
cipherBytes, 0, cipherBytes.Length);
|
|
|
|
return Encoding.UTF8.GetString(decryptedBytes);
|
|
}
|
|
}
|
|
}
|
|
}
|