技术文摘
C#中DES算法加密解密实例剖析
2025-01-02 02:42:55 小编
C#中DES算法加密解密实例剖析
在当今数字化时代,数据安全至关重要。加密算法作为保护数据隐私的关键技术,被广泛应用于各个领域。其中,DES(Data Encryption Standard)算法是一种对称加密算法,具有高效、可靠的特点。本文将通过一个C#实例来深入剖析DES算法的加密和解密过程。
我们需要了解DES算法的基本原理。DES算法使用相同的密钥进行加密和解密,它将数据分成64位的块,并通过一系列复杂的置换、替换和异或操作来实现加密。密钥长度为56位,加上8位的奇偶校验位,总共64位。
在C#中实现DES算法加密解密,需要使用System.Security.Cryptography命名空间下的相关类。以下是一个简单的示例代码:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string originalText = "Hello, World!";
string key = "12345678";
byte[] encryptedBytes = Encrypt(originalText, key);
string decryptedText = Decrypt(encryptedBytes, key);
Console.WriteLine("原始文本: " + originalText);
Console.WriteLine("加密后的数据: " + Convert.ToBase64String(encryptedBytes));
Console.WriteLine("解密后的文本: " + decryptedText);
}
static byte[] Encrypt(string plainText, string key)
{
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = Encoding.UTF8.GetBytes(key);
des.IV = Encoding.UTF8.GetBytes(key);
using (ICryptoTransform encryptor = des.CreateEncryptor())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(plainText);
return encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
}
}
}
static string Decrypt(byte[] encryptedBytes, string key)
{
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = Encoding.UTF8.GetBytes(key);
des.IV = Encoding.UTF8.GetBytes(key);
using (ICryptoTransform decryptor = des.CreateDecryptor())
{
byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
}
在上述代码中,我们首先定义了原始文本和密钥。然后,通过Encrypt方法对原始文本进行加密,得到加密后的数据。最后,使用Decrypt方法对加密后的数据进行解密,恢复原始文本。
通过这个实例,我们可以看到DES算法在C#中的具体应用。在实际开发中,我们可以根据需求对代码进行进一步优化和扩展,以满足不同的安全需求。
- 有哪些可免费获取IP地区信息的API接口
- 免费获取IP地址所属地区信息的API接口推荐有哪些
- 打包Python脚本以在不同Python版本下正常运行的方法
- 有哪些好用的可免费获取IP地址所属地区信息的API接口
- 免费查IP地址所属地区的方法有哪些
- Python模拟PHP的array_column函数功能的方法
- 免费的 IP 地址归属地查询 API 接口有哪些
- Python实现类似PHP array_column函数功能的方法
- Python使用with语句打开文件时怎样防止因目录不存在导致创建失败
- Python怎样高效提取列表中字典特定列的值
- Python装饰器:深入了解功能增强
- Python with语句打开文件时优雅处理文件不存在情况的方法
- tqdm进度条与print()函数冲突时的调试方法
- Python避免tqdm进度条与print函数冲突的方法
- Python with语句打开文件 如何创建不存在的文件或目录