hippiewho
hippiewho
CC#
Created by hippiewho on 10/20/2022 in #help
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;
}
}
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;
}
}
8 replies