在C#中,DES(数据加密标准)是一种对称加密算法,用于加密和解密数据。它使用56位密钥进行加密,并且具有较高的安全性和速度。以下是一个简单的C#代码示例,展示了如何使用DES算法进行加密和解密操作:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace DES_Encryption_Example
{
class Program
{
static void Main(string[] args)
{
string original = "This is a test message.";
string key = "1234567890123456"; // 56位密钥
// 加密
string encrypted = Encrypt(original, key);
Console.WriteLine("Encrypted: " + encrypted);
// 解密
string decrypted = Decrypt(encrypted, key);
Console.WriteLine("Decrypted: " + decrypted);
}
static string Encrypt(string plainText, string key)
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(keyBytes, null), CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
static string Decrypt(string cipherText, string key)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(keyBytes, null), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.FlushFinalBlock();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
}
}
在这个示例中,我们使用了DESCryptoServiceProvider类来实现加密和解密操作。我们将原始文本和密钥转换为字节数组,然后使用DES算法对其进行加密和解密。最后,我们将加密后的数据转换为Base64字符串,以便在需要时进行传输和存储。
需要注意的是,DES算法的安全性相对较低,因此建议使用更加安全的加密算法,例如AES(高级加密标准)。
领取专属 10元无门槛券
手把手带您无忧上云