技术文摘
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#中的具体应用。在实际开发中,我们可以根据需求对代码进行进一步优化和扩展,以满足不同的安全需求。
- Python 如何自动识别 URL 的协议类型(HTTP 或 HTTPS)
- 哪种编程语言最好
- 用Go把两个切片转换为JSON的方法
- Filebeat不读取 -c 指定配置文件而从 /etc/filebeat.yml 加载配置的原因
- Go语言中接收器函数调用未初始化类型问题的解决方法
- Filebeat 使用 -c 参数却仍加载 etc 中配置文件的原因
- 把用Scrapy编写的爬虫程序封装成API的方法
- Go语言中导入包并用init函数初始化变量后仍无法访问的原因
- 如何解决 Python 调用 MySQL 语句时的报错问题
- 系统重装后Git拉取代码提示输密码的解决方法
- Go泛型嵌套下WowMap[T]类型的实例化方法
- Selenium 添加 Cookie 后无法登录的原因探讨
- Qt窗口在mouseMoveEvent事件中崩溃:Mwindow对象为何没有mouse_x属性
- Scrapy框架获取响应内容为空的排查方法
- Linux 安装 Levenshtein 时如何解决 “‘PyString_Type’ 未声明” 错误