mcdiscordbot/MinecraftDiscordBot/AesCipher.cs

44 lines
1.2 KiB
C#
Raw Normal View History

using System.Security.Cryptography;
namespace MinecraftDiscordBot;
public class AesCipher : ICipher {
private readonly byte[] key;
private readonly byte[] iv;
public AesCipher() {
using var aes = Aes.Create();
aes.GenerateKey();
aes.GenerateIV();
key = aes.Key;
iv = aes.IV;
}
public byte[] Encrypt(byte[] plain) {
using var aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
var transformer = aes.CreateEncryptor();
using var ms = new MemoryStream();
using (var cs = new CryptoStream(ms, transformer, CryptoStreamMode.Write))
cs.Write(plain);
return ms.ToArray();
}
public byte[] Decrypt(byte[] cipher) {
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
var transformer = aes.CreateDecryptor();
using MemoryStream ms = new MemoryStream(cipher);
using CryptoStream cs = new CryptoStream(ms, transformer, CryptoStreamMode.Read);
using MemoryStream os = new MemoryStream();
cs.CopyTo(os);
return os.ToArray();
}
}
public interface ICipher {
byte[] Decrypt(byte[] cipher);
byte[] Encrypt(byte[] plain);
}