2018-06-15 02:57:03 +02:00
|
|
|
|
using System.IO;
|
2017-06-11 09:03:44 +02:00
|
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace Teknik.Utilities.Cryptography
|
|
|
|
|
{
|
|
|
|
|
public static class AES
|
|
|
|
|
{
|
|
|
|
|
public static byte[] Encrypt(byte[] value, byte[] key, byte[] iv, int keyLength, int blockLength, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
|
|
|
|
|
{
|
|
|
|
|
using (var cipher = CreateCipher(key, iv, keyLength, blockLength, feedbackSize, mode, paddingMode))
|
|
|
|
|
{
|
|
|
|
|
return Encrypt(cipher, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
public static byte[] Decrypt(byte[] value, byte[] key, byte[] iv, int keyLength, int blockLength, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
|
|
|
|
|
{
|
|
|
|
|
using (var cipher = CreateCipher(key, iv, keyLength, blockLength, feedbackSize, mode, paddingMode))
|
|
|
|
|
{
|
|
|
|
|
return Decrypt(cipher, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-23 05:51:09 +02:00
|
|
|
|
public static byte[] Encrypt(Aes cipher, byte[] value)
|
2017-06-11 09:03:44 +02:00
|
|
|
|
{
|
|
|
|
|
byte[] encryptedBytes;
|
|
|
|
|
using (var encryptor = cipher.CreateEncryptor())
|
|
|
|
|
using (MemoryStream ms = new MemoryStream())
|
|
|
|
|
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
|
|
|
|
using (var bw = new BinaryWriter(cs, Encoding.UTF8))
|
|
|
|
|
{
|
|
|
|
|
bw.Write(value);
|
|
|
|
|
bw.Close();
|
|
|
|
|
|
|
|
|
|
encryptedBytes = ms.ToArray();
|
|
|
|
|
}
|
|
|
|
|
return encryptedBytes;
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-23 05:51:09 +02:00
|
|
|
|
public static byte[] Decrypt(Aes cipher, byte[] value)
|
2017-06-11 09:03:44 +02:00
|
|
|
|
{
|
|
|
|
|
byte[] decryptedBytes;
|
|
|
|
|
using (var decryptor = cipher.CreateDecryptor())
|
|
|
|
|
using (MemoryStream ms = new MemoryStream())
|
|
|
|
|
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
|
|
|
|
|
using (var bw = new BinaryWriter(cs, Encoding.UTF8))
|
|
|
|
|
{
|
|
|
|
|
bw.Write(value);
|
|
|
|
|
bw.Close();
|
|
|
|
|
|
|
|
|
|
decryptedBytes = ms.ToArray();
|
|
|
|
|
}
|
|
|
|
|
return decryptedBytes;
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-23 05:51:09 +02:00
|
|
|
|
public static Aes CreateCipher(byte[] key, byte[] iv, int keyLength, int blockSize, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
|
2017-06-11 09:03:44 +02:00
|
|
|
|
{
|
2022-05-23 05:51:09 +02:00
|
|
|
|
Aes cipher = Aes.Create();
|
2017-06-11 09:03:44 +02:00
|
|
|
|
cipher.Mode = mode;
|
|
|
|
|
cipher.Padding = paddingMode;
|
|
|
|
|
cipher.Key = key;
|
|
|
|
|
cipher.IV = iv;
|
|
|
|
|
cipher.KeySize = keyLength;
|
|
|
|
|
cipher.BlockSize = blockSize;
|
|
|
|
|
cipher.FeedbackSize = feedbackSize;
|
|
|
|
|
|
|
|
|
|
return cipher;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|