using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AES_2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = EncryptString(textBox1.Text, textBox3.Text);
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = DecryptString(textBox2.Text, textBox3.Text);
}
public static string EncryptString(string message, string key)
{
key = Get_SHA256_Hash(key).Substring(0, 32);
var keyBytes = Convert.FromBase64String(key);
var aes = new AesCryptoServiceProvider();
var iv = aes.IV;
using (var memStream = new System.IO.MemoryStream())
{
memStream.Write(iv, 0, iv.Length); // Add the IV to the first 16 bytes of the encrypted value
using (var cryptStream = new CryptoStream(memStream, aes.CreateEncryptor(keyBytes, aes.IV), CryptoStreamMode.Write))
{
using (var writer = new System.IO.StreamWriter(cryptStream))
{
writer.Write(message);
}
}
var buf = memStream.ToArray();
return Convert.ToBase64String(buf, 0, buf.Length);
}
}
public static string DecryptString(string encryptedValue, string key)
{
key = Get_SHA256_Hash(key).Substring(0, 32);
var bytes = Convert.FromBase64String(encryptedValue);
var keyBytes = Convert.FromBase64String(key);
var aes = new AesCryptoServiceProvider();
using (var memStream = new System.IO.MemoryStream(bytes))
{
var iv = new byte[16];
memStream.Read(iv, 0, 16); // Pull the IV from the first 16 bytes of the encrypted value
using (var cryptStream = new CryptoStream(memStream, aes.CreateDecryptor(keyBytes, iv), CryptoStreamMode.Read))
{
using (var reader = new System.IO.StreamReader(cryptStream))
{
return reader.ReadToEnd();
}
}
}
}
public static string Get_SHA256_Hash(string str)
{
byte[] sha256Bytes = Encoding.UTF8.GetBytes(str);
SHA256Managed sha256 = new SHA256Managed();
byte[] bytes = sha256.ComputeHash(sha256Bytes);
return BitConverter.ToString(bytes).Replace("-", "").ToUpper();
}
}
}