using IOTContainer.Common;
using System;
using System.Security.Cryptography;
using System.Text;
namespace IOTContainer.Common
{
public class SecurityHelper
{
#region AES加密解密
///
/// 128位处理key
///
/// 原字节
/// 处理key
///
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;
}
///
/// 使用AES加密字符串,按128位处理key
///
/// 加密内容
/// 秘钥,需要128位、256位.....
/// Base64字符串结果
public static string AesEncrypt(string content, bool autoHandle = true)
{
byte[] keyArray = Encoding.UTF8.GetBytes(StringDecode(ComParameters.Parameters.SecurityKey));
if (autoHandle)
{
keyArray = GetAesKey(keyArray, StringDecode(ComParameters.Parameters.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);
}
///
/// 使用AES解密字符串,按128位处理key
///
/// 内容
/// 秘钥,需要128位、256位.....
/// UTF8解密结果
public static string AesDecrypt(string content, bool autoHandle = true)
{
byte[] keyArray = Encoding.UTF8.GetBytes(StringDecode(ComParameters.Parameters.SecurityKey));
if (autoHandle)
{
keyArray = GetAesKey(keyArray, StringDecode(ComParameters.Parameters.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
///
/// 解密(反转再base64解码),常规配置,例如密码
///
///
///
public static string StringDecode(string str)
{
string result = string.Empty;
try
{
if (!string.IsNullOrEmpty(str))
{
char[] arr = str.ToCharArray();
Array.Reverse(arr);
result = Encoding.UTF8.GetString(Convert.FromBase64String(new string(arr)));
}
}
catch (Exception ex)
{
Log.MyLog.WriteLogFile(ex.ToString());
}
return result;
}
}
}