技术文摘
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#中的具体应用。在实际开发中,我们可以根据需求对代码进行进一步优化和扩展,以满足不同的安全需求。
- CentOS 7系统下MySQL压缩包安装指南
- mysql安装后如何使用 安装好mysql的使用教程
- 绿色版 MySQL 安装与使用教程
- mysql安装后怎样使用?mysql安装及简单使用教程
- Linux下MySQL最新安装配置全流程教程
- DOS环境下安装MySQL的详细教程
- MySQL 5.5安装完成后在哪里使用教程
- MySQL 终端:实现登录、管理用户与权限
- MySQL卸载方法及详细步骤
- GOLANG中GIN、GORM、TESTIFY与MYSQL的集成测试
- 借助通用查询日志提升 MySQL 调试技巧
- MySQL 常见面试问题
- Cara Menginstal MySQL di Ubuntu
- 如何修复 MySQL 意外关闭错误
- 数据库中无主键或唯一约束的行的更新插入操作