首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

C#中的DES加密

在C#中,DES(数据加密标准)是一种对称加密算法,用于加密和解密数据。它使用56位密钥进行加密,并且具有较高的安全性和速度。以下是一个简单的C#代码示例,展示了如何使用DES算法进行加密和解密操作:

代码语言:csharp
复制
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(高级加密标准)。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

17分33秒

17_尚硅谷JAVA-des加密

20分17秒

golang教程 Go区块链 04 des加密解密 学习猿地

15分18秒

golang教程 Go区块链 06 des加密解密 学习猿地

10分14秒

小编捡垃圾捡的加密U盾!

1分53秒

3种JS加密,你觉的哪个更好?

17分5秒

051 尚硅谷-Linux云计算-网络服务-VSFTP-openssl+vsftp加密传输(中)

6分23秒

16_尚硅谷JAVA-对称加密的原理

1分35秒

双分区的加密SSD改造公私分明的移动硬盘

1分57秒

JS混淆加密:JShaman的四种打开方式

7分34秒

11. 尚硅谷_Shiro_密码的MD5加密.avi

6分47秒

40-基本使用-同样不安全的非对称加密算法

7分11秒

12. 尚硅谷_Shiro_密码的MD5盐值加密.avi

领券