.NET: Microsoft Technologies based on the .NET software framework. Runtime: An environment required to run apps that aren't compiled to machine language.
Hi @Prabs ,
I made some simplifications and modifications on the previous example, and it can now run correctly.
You can refer to the following code.
public string Encrypt(string PlainText, String Salt = "Kosher", String InitialVector = "OFRna73m*aze01xY")
{
if (string.IsNullOrEmpty(PlainText))
{
return string.Empty;
}
SHA256Managed sHA256Managed = new SHA256Managed();
byte[] key = sHA256Managed.ComputeHash(Encoding.ASCII.GetBytes(Salt));
byte[] iv = Encoding.ASCII.GetBytes(InitialVector);
using (var SymmetricKey = new AesCng()
{
Key = key,
IV = iv,
KeySize = 256,
BlockSize = 128,
Mode = CipherMode.CBC,
})
{
using (var transform = SymmetricKey.CreateEncryptor(key, iv))
{
var inputBytes = Encoding.UTF8.GetBytes(PlainText);
var encryptedBytes = transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
return Convert.ToBase64String(encryptedBytes);
}
}
}
public string Decrypt(string CipherText, String Salt = "Kosher", String InitialVector = "OFRna73m*aze01xY")
{
if (string.IsNullOrEmpty(CipherText))
{
return string.Empty;
}
SHA256Managed sHA256Managed = new SHA256Managed();
byte[] key = sHA256Managed.ComputeHash(Encoding.ASCII.GetBytes(Salt));
byte[] iv = Encoding.ASCII.GetBytes(InitialVector);
using (var SymmetricKey = new AesCng()
{
Key = key,
IV = iv,
KeySize = 256,
BlockSize = 128,
Mode = CipherMode.CBC,
})
{
using (var transform = SymmetricKey.CreateDecryptor(key, iv))
{
var inputBytes = Convert.FromBase64String(CipherText);
var PlainTextBytes = transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
return Encoding.UTF8.GetString(PlainTextBytes);
}
}
}
Hope the code above colud be helpful.
Best Regards.
Jiachen Li
----------
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.