I have update the my project fretwork from .Net Core 3.1 to .Net 6. bellow code working fine with 3.1 but not working with .Net 6. In .net 6 I have missing some data, Like if I encrypt "Ravi Chandra" and than decrypt, I got "Ravi Chand". please suggest any solution.
public class AESEncryption
{
private const string _IV = "Encryption";
private const string _Key = "TestEncryption";
private const int _BlockSize = 128;
public static string Encrypt(string plainText)
{
if (string.IsNullOrEmpty(plainText))
return ""; byte[] bytes = Encoding.Unicode.GetBytes(plainText);
using (Aes crypt = Aes.Create())
{
using (HashAlgorithm hash = MD5.Create())
{
crypt.BlockSize = _BlockSize;
crypt.Key = hash.ComputeHash(Encoding.Unicode.GetBytes(_Key));
crypt.IV = hash.ComputeHash(Encoding.Unicode.GetBytes(_IV)); using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream =
new CryptoStream(memoryStream, crypt.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(bytes, 0, bytes.Length);
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
public static string Decrypt(string ciphertext)
{
if (string.IsNullOrEmpty(ciphertext))
return ""; byte[] bytes = Convert.FromBase64String(ciphertext);
using (Aes crypt = Aes.Create())
{
using (HashAlgorithm hash = MD5.Create())
{
crypt.Key = hash.ComputeHash(Encoding.Unicode.GetBytes(_Key));
crypt.IV = hash.ComputeHash(Encoding.Unicode.GetBytes(_IV));
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
using (CryptoStream cryptoStream =
new CryptoStream(memoryStream, crypt.CreateDecryptor(), CryptoStreamMode.Read))
{
byte[] decryptedBytes = new byte[bytes.Length];
cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);
return Encoding.Unicode.GetString(decryptedBytes).Replace("\0", "");
}
}
}
}
}
}