using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
public class AesHelper
{
/// <summary>
/// AES加密,可设置秘钥任意长度
/// </summary>
/// <param name="content"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string Encrypt(string content, string key)
{
try
{
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Key = EncryptJavaAes(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] byteContent = Encoding.UTF8.GetBytes(content);
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] byteResult = encryptor.TransformFinalBlock(byteContent, 0, byteContent.Length);
StringBuilder sb = new StringBuilder();
foreach (byte b in byteResult)
{
sb.Append(b.ToString("X2")); // 将每个字节转换为两位的十六进制表示
}
return sb.ToString();
}
}
catch (Exception e)
{
Console.WriteLine("Encryption error: " + e);
}
return null;
}
/// <summary>
/// AES解密,可设置秘钥任意长度
/// </summary>
/// <param name="content"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string Decrypt(string content, string key)
{
try
{
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Key = EncryptJavaAes(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] byteContent = new byte[content.Length / 2];
for (int i = 0; i < content.Length / 2; i++)
{
byteContent[i] = Convert.ToByte(content.Substring(i * 2, 2), 16); // 将十六进制字符串转换为字节
}
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] byteResult = decryptor.TransformFinalBlock(byteContent, 0, byteContent.Length);
return Encoding.UTF8.GetString(byteResult);
}
}
catch (Exception e)
{
Console.WriteLine("Decryption error: " + e);
}
return null;
}
/// <summary>
/// java的SHA1PRNG算法
/// </summary>
/// <param name="aesKey"></param>
/// <returns></returns>
private static byte[] EncryptJavaAes(string aesKey)
{
byte[] keyArray = null;
using (var sha1 = new SHA1CryptoServiceProvider())
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(aesKey));
var rd = sha1.ComputeHash(hash);
keyArray = rd.Take(16).ToArray();
}
return keyArray;
}
}
net7 AES 加解密算法,其中key使用sha1prng加密
最新推荐文章于 2024-06-17 11:29:13 发布