Hi nauna,
The length of a base64 encoded string is always a multiple of 4.
So while decrypting, the string is not a valid base 64 char array, so the error.
I have created a sample as per your shared code. Please refer sample below.
HTML
<u>Encrypt</u>
<br />
Enter text:
<br />
<asp:TextBox ID="txtOriginal" runat="server"></asp:TextBox>
<asp:Button ID="btnEncrypt" runat="server" Text="Encrypt" OnClick="Encrypt" /><br />
<br />
Encrypted Text:
<asp:Label ID="lblEncryptedText" runat="server"></asp:Label><br />
<br />
<u>Decrypt</u>
<br />
Enter Encrypted Text:
<br />
<asp:TextBox ID="txtDecrypt" runat="server"></asp:TextBox>
<asp:Button ID="btnDecrypt" runat="server" Text="Decrupt" OnClick="Decrypt" /><br />
<br />
Original Text:
<asp:Label ID="lblDecryptedText" runat="server"></asp:Label>
Namespaces
using System.IO;
using System.Text;
using System.Security.Cryptography;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
txtOriginal.Text = GenerateRandomNo();
}
}
private Random _random = new Random();
public string GenerateRandomNo()
{
return _random.Next(0, 9999).ToString("D4");
}
protected void Encrypt(object sender, EventArgs e)
{
lblEncryptedText.Text = this.Encrypt(txtOriginal.Text.Trim());
}
public string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
protected void Decrypt(object sender, EventArgs e)
{
lblDecryptedText.Text = this.Decrypt(txtDecrypt.Text.Trim());
}
public string Decrypt(string cipherText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
Screenshot