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.
iot/labs/Teacher/TeacherExt/AesHelper.cs

119 lines
3.4 KiB

using Infrastructure.Extensions;
using Microsoft.Extensions.Configuration;
using System;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace TeacherExt
{
public class AesHelper
{
private readonly IConfiguration _config;
public AesHelper(IConfiguration config)
{
this._config = config;
}
public string Decrypt(string input)
{
try
{
var data = HexStringToByteArray(input);
return Encoding.UTF8.GetString(AesDecrypt(data)).Trim();
}
catch (Exception ex)
{
ex.PrintStack();
}
return input;
}
public string Encrypt(string input)
{
try
{
var data = AesEncrypt(Encoding.UTF8.GetBytes(input));
return BytesToHex(data);
}
catch (Exception ex)
{
ex.PrintStack();
}
return input;
}
private byte[] AesEncrypt(byte[] plainText)
{
using var aes = CreateAes();
using var encryptor = aes.CreateEncryptor();
return encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
}
private byte[] AesDecrypt(byte[] cipherText)
{
using var aes = CreateAes();
using var decryptor = aes.CreateDecryptor();
return decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
}
private Aes CreateAes()
{
var password = this._config.GetValue<string>("password");
var key = Encoding.UTF8.GetBytes(password);
//var iv = HexStringToByteArray("DsideaL4r5t6y7u!@#");
var aesAlg = Aes.Create();
aesAlg.KeySize = 128;
aesAlg.Key = AESCreateKey(key, aesAlg.KeySize / 8);
aesAlg.IV = new byte[16];
aesAlg.BlockSize = 128;
aesAlg.Mode = CipherMode.ECB;
aesAlg.Padding = PaddingMode.PKCS7;
return aesAlg;
}
private static byte[] AESCreateKey(byte[] key, int keyLength)
{
// Create the real key with the given key length.
byte[] realkey = new byte[keyLength];
// XOR each byte of the Key given with the real key until there's nothing left.
// This allows for keys longer than our Key Length and pads short keys to the required length.
for (int i = 0; i < key.Length; i++)
{
realkey[i % keyLength] ^= key[i];
}
return realkey;
}
private static byte[] HexStringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public string BytesToHex(byte[] bytes)
{
if (bytes is null)
{
throw new ArgumentNullException(nameof(bytes));
}
var hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
hex.AppendFormat(CultureInfo.InvariantCulture, "{0:X2}", b);
}
return hex.ToString();
}
}
}