Whenever I try to call Decrypt function on stored password in DB, I receive Invalid length for a Base-64 char array or string. Decrypt code:
public static string Decrypt(string encryptedText)
{
// byte[] cipherTextBytes = Convert.FromBase64String(encryptedText)); OLD ONE
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText.Replace(' ', '+')); //NEW
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
var memoryStream = new MemoryStream(cipherTextBytes);
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
}
I have found that converting string like this causes this error:
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText)); OLD ONE
So insread it should be done like this:
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText.Replace(' ', '+'));
But I still get the same error and basically all solutions I found on google point to this kind of solution which doesn't help me. Anyone could explain what's wrong with it? Thanks.