I wrote a code for encrypting and decrypting sample text using the AES algorithm. When I click the first button, I want to encrypt the string which will display on the textbox1 and for second button click, decrypted value should display on textbox2.
This is the code for that:
public partial class _Default : Page
{
public byte[] key = null; public byte[] iv = null; public byte[] bytesToEncrypt = null; public static byte[] encryptedBytes = null; public byte[] decryptedBytes = null;
protected void Page_Load(object sender, EventArgs e)
{
RijndaelManaged aesAlg = new RijndaelManaged();
aesAlg.GenerateKey();
aesAlg.GenerateIV();
key = aesAlg.Key;
iv = aesAlg.IV;
}
protected void Button1_Click(object sender, EventArgs e)
{
// original bytes
bytesToEncrypt = new byte[TextBox2.Text.ToString().Length * sizeof(char)];
encryptedBytes = CryptoAes.Encrypt(bytesToEncrypt, key, iv);
TextBox1.Text = Convert.ToBase64String(encryptedBytes);
byte[] bytesToEncrypt1 = new byte[TextBox2.Text.Length];
decryptedBytes = CryptoAes.Decrypt(encryptedBytes, key, iv);//working here.
}
protected void Button2_Click(object sender, EventArgs e)
{
var s = Convert.FromBase64String(TextBox1.Text);
decryptedBytes = CryptoAes.Decrypt(encryptedBytes, key, iv);
TextBox2.Text = System.Text.Encoding.Unicode.GetString(decryptedBytes);//not working
}
}
internal sealed class CryptoAes
{
public static byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
{
byte[] encryptedData = null;
if (data == null)
throw new ArgumentNullException("data");
if (data == key)
throw new ArgumentNullException("key");
if (data == iv)
throw new ArgumentNullException("iv");
using (RijndaelManaged aesAlg = new RijndaelManaged())
{
aesAlg.Key = key;
aesAlg.IV = iv;
aesAlg.Padding = PaddingMode.Zeros;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);
}
return encryptedData;
}
public static byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
{
byte[] decryptedData = null;
if (data == null)
throw new ArgumentNullException("data");
if (data == key)
throw new ArgumentNullException("key");
if (data == iv)
throw new ArgumentNullException("iv");
using (RijndaelManaged aesAlg = new RijndaelManaged())
{
aesAlg.Key = key;
aesAlg.IV = iv;
aesAlg.Padding = PaddingMode.Zeros;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);
}
return decryptedData;
}
}
For the first button click the decrypt is working fine. But when I click the second button the decrypted text shows some junk characters.
To figure out this I made the encryptedBytes as static and reuse it when I click the second button, but still the same output with junk values. I wonder how the same input gives the correct output when I click the first button.
Can anyone help me to sort out this?
bytesToEncryptjust be an empty array? what are you trying to encrypt, the data inTextBox2.Text?