I can encrypt just fine. However, if an encrypted string doesn't end with the equal letter "=" at the end, then it won't decrypt properly and I get an empty string (or so it seems).
What works:
+FmU/RQ5jP86j7F6bPjddA==
YQXBLjwEXEGgYz8xnF10O9QqO/vj5DI8PpZZCvfhG1RGHAYumtWrAEBfdSSOkF79vzVCSQ+ejO3uMIDSmY43bw==
What won't work:
xnyfqPsvrEOK8AoQz2p7AGFHoHncZ/wB/R3qr+scts6nLI2xauWnbmYsXsU3iMoT
encrypt function:
public string EncryptionKey = "abc123";
public string encrypt(string input)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(input);
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();
}
input = Convert.ToBase64String(ms.ToArray());
}
}
return input;
}
Here's the decrypt function:
public string decrypt(string cipherText)
{
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();
}
return Encoding.Unicode.GetString(ms.ToArray());
}
}
}
Any idea how to solve this?
EDIT: Added encrypt function
EDIT 2:
This is how I'm calling the encrypt-function (before I send the string via socket.io)
ASCIIEncoding aEncoding = new ASCIIEncoding();
byte[] sendMsg = new byte[1500];
sendMsg = aEncoding.GetBytes((encrypt(txtMsg.Text)));