I need to store some encrypted data and then (in second time) read the original value, I don't need very strong encryption, just much as the user can't be able to manipulate those string(s).
I'm trying this code:
public static string Encrypt(string plainText)
{
if (Settings.LicenseOK())
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
var symmetricKey = Aes.Create();
//symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.Zeros;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor();
using MemoryStream ms = new MemoryStream();
using CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
cs.Write(plainTextBytes, 0, plainTextBytes.Length);
cs.FlushFinalBlock();
ms.Flush();
return Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.None);
}
else
throw (new Exception("Errore nella DLL GDWS"));
}
public static string Decrypt(string cipherText)
{
if (Settings.LicenseOK())
{
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
var symmetricKey = Aes.Create();
//symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.Zeros;
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
ICryptoTransform decryptor = symmetricKey.CreateDecryptor();
using MemoryStream ms = new MemoryStream(cipherTextBytes);
using CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
cs.Read(plainTextBytes);
return Encoding.UTF8.GetString(plainTextBytes);
}
else
throw (new Exception("Errore nella DLL GDWS"));
}
}
But every time I encrypt a string, the encrypted one changes (I think it has to remain the same or it can't be decrypted), and I cannot revert the process (decryption) (the decryption process takes to an incomprehensible yet always different string).
Please help me.
You have to preserve the same key between encryption and decryption.