12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using IES.ExamServer.Helper;
- using System;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.Json;
- namespace IES.ExamServer.Helpers
- {
- public class AESHelper
- {
- private static readonly byte[] Key = Encoding.UTF8.GetBytes(Constant._MusicAIServerAESKey);
- private static readonly byte[] IV = Encoding.UTF8.GetBytes(Constant._MusicAIServerAESIv);
- // 解密方法
- public static string Decrypt(string encryptedText)
- {
- Console.WriteLine("解密前的内容:", encryptedText);
- if (string.IsNullOrEmpty(encryptedText))
- {
- return encryptedText;
- }
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- aesAlg.Mode = CipherMode.CBC;
- aesAlg.Padding = PaddingMode.PKCS7;
- ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
- byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
- byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
- string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
- Console.WriteLine("解密后的内容:", decryptedText);
- if (decryptedText.StartsWith("{"))
- {
- return JsonSerializer.Serialize(JsonSerializer.Deserialize<object>(decryptedText));
- }
- else
- {
- return decryptedText;
- }
- }
- }
- // 加密方法
- public static string Encrypt(string plainText)
- {
- Console.WriteLine("加密前的内容:", plainText);
- if (string.IsNullOrEmpty(plainText))
- {
- return plainText;
- }
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- aesAlg.Mode = CipherMode.CBC;
- aesAlg.Padding = PaddingMode.PKCS7;
- ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
- byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
- byte[] encryptedBytes = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
- string encryptedText = Convert.ToBase64String(encryptedBytes);
- Console.WriteLine("加密后的内容:", encryptedText);
- return encryptedText;
- }
- }
- }
- }
|