Hi @zequion , Welcome to Microsoft Q&A,
Use the TripleDESCryptoServiceProvider class to ensure that the same encryption and decryption logic is used on .NET Framework and .NET Core, avoiding issues caused by platform differences.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class TripleDESEncryption
{
public static byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
{
using (TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider())
{
tdes.Key = key;
tdes.IV = iv;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.PKCS7;
using (ICryptoTransform encryptor = tdes.CreateEncryptor())
{
return PerformCryptography(data, encryptor);
}
}
}
public static byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
{
using (TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider())
{
tdes.Key = key;
tdes.IV = iv;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.PKCS7;
using (ICryptoTransform decryptor = tdes.CreateDecryptor())
{
return PerformCryptography(data, decryptor);
}
}
}
private static byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
}
class Program
{
static void Main()
{
byte[] key = Encoding.UTF8.GetBytes("123456789012345678901234"); // 24 bytes for TripleDES
byte[] iv = Encoding.UTF8.GetBytes("12345678"); // 8 bytes for TripleDES
byte[] data = Encoding.UTF8.GetBytes("Hello World!");
// Encrypt the data
byte[] encryptedData = TripleDESEncryption.Encrypt(data, key, iv);
Console.WriteLine("Encrypted data: " + Convert.ToBase64String(encryptedData));
// Decrypt the data
byte[] decryptedData = TripleDESEncryption.Decrypt(encryptedData, key, iv);
Console.WriteLine("Decrypted data: " + Encoding.UTF8.GetString(decryptedData));
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
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.