C#C
C#4y ago
hippiewho

CryptoStream decrypt encrypt

I have a class to encrypt and decrypt strings but for some reason i get an exception:

System.Security.Cryptography.CryptographicException: 'Padding is invalid and cannot be removed.'

public class BasicEncryption
    {
        public string Encrypt(string rawValue)
        {
            using Aes aes = Aes.Create();
            using ICryptoTransform encryptor = aes.CreateEncryptor();
            using MemoryStream memoryStream = new MemoryStream();
            using CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
            using StreamWriter swEncrypt = new StreamWriter(cryptoStream);
            swEncrypt.Write(rawValue);
            swEncrypt.Flush();
            var memBytes = memoryStream.ToArray();
            return Convert.ToBase64String(memBytes);
        }

        public string Decrypt(string encryptedValue)
        {
            using Aes aes = Aes.Create();
            byte[] encryptedData = Convert.FromBase64String(encryptedValue);
            using ICryptoTransform decryptor = aes.CreateDecryptor();
            using MemoryStream memoryStream = new MemoryStream(encryptedData);
            using CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            using StreamReader srDecrypt = new StreamReader(cryptoStream);
            string plaintext = srDecrypt.ReadToEnd();
            return plaintext;
        }
    }
Was this page helpful?