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.
95 lines
2.6 KiB
95 lines
2.6 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Container.Common
|
|
{
|
|
/// <summary>
|
|
/// 加密解密类
|
|
/// </summary>
|
|
public class SecurityHelper
|
|
{
|
|
#region AES加密解密
|
|
private static App app = ((App)System.Windows.Application.Current);
|
|
/// <summary>
|
|
/// 128位处理key
|
|
/// </summary>
|
|
/// <param name="keyArray">原字节</param>
|
|
/// <param name="key">处理key</param>
|
|
/// <returns></returns>
|
|
private static byte[] GetAesKey(byte[] keyArray, string key)
|
|
{
|
|
byte[] newArray = new byte[16];
|
|
if (keyArray.Length < 16)
|
|
{
|
|
for (int i = 0; i < newArray.Length; i++)
|
|
{
|
|
if (i >= keyArray.Length)
|
|
{
|
|
newArray[i] = 0;
|
|
}
|
|
else
|
|
{
|
|
newArray[i] = keyArray[i];
|
|
}
|
|
}
|
|
}
|
|
else
|
|
newArray = keyArray;
|
|
|
|
return newArray;
|
|
}
|
|
/// <summary>
|
|
/// 使用AES加密字符串,按128位处理key
|
|
/// </summary>
|
|
/// <param name="content">加密内容</param>
|
|
/// <param name="key">秘钥,需要128位、256位.....</param>
|
|
/// <returns>Base64字符串结果</returns>
|
|
public static string AesEncrypt(string content, bool autoHandle = true)
|
|
{
|
|
byte[] keyArray = Encoding.UTF8.GetBytes(app.SecurityKey);
|
|
if (autoHandle)
|
|
{
|
|
keyArray = GetAesKey(keyArray, app.SecurityKey);
|
|
}
|
|
byte[] toEncryptArray = Encoding.UTF8.GetBytes(content);
|
|
|
|
SymmetricAlgorithm des = Aes.Create();
|
|
des.Key = keyArray;
|
|
des.Mode = CipherMode.ECB;
|
|
des.Padding = PaddingMode.PKCS7;
|
|
ICryptoTransform cTransform = des.CreateEncryptor();
|
|
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
|
return Convert.ToBase64String(resultArray);
|
|
}
|
|
/// <summary>
|
|
/// 使用AES解密字符串,按128位处理key
|
|
/// </summary>
|
|
/// <param name="content">内容</param>
|
|
/// <param name="key">秘钥,需要128位、256位.....</param>
|
|
/// <returns>UTF8解密结果</returns>
|
|
public static string AesDecrypt(string content, bool autoHandle = true)
|
|
{
|
|
byte[] keyArray = Encoding.UTF8.GetBytes(app.SecurityKey);
|
|
if (autoHandle)
|
|
{
|
|
keyArray = GetAesKey(keyArray, app.SecurityKey);
|
|
}
|
|
byte[] toEncryptArray = Convert.FromBase64String(content);
|
|
|
|
SymmetricAlgorithm des = Aes.Create();
|
|
des.Key = keyArray;
|
|
des.Mode = CipherMode.ECB;
|
|
des.Padding = PaddingMode.PKCS7;
|
|
|
|
ICryptoTransform cTransform = des.CreateDecryptor();
|
|
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
|
|
|
return Encoding.UTF8.GetString(resultArray);
|
|
}
|
|
#endregion
|
|
}
|
|
}
|
|
|