c# - 使用用户输入密码使用 DES 加密

标签 c# encryption des

我还在学习密码学。我正在尝试在 C# 中创建一个简单的静态函数,将字符串加密为 DES(使用 Base64 输出)。我了解到 DES 使用 8 字节作为其 key 。我想让用户输入任意长度的字符串,用它作为加密消息的 key ,然后将其转换为Base64。示例在此 site .

public static string EncryptDES(string phrase, string key)
{
    string encrypted = "";

    byte[] phraseBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(phrase);
    byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

    System.Security.Cryptography.MD5CryptoServiceProvider hashMD5Provider 
                                = new System.Security.Cryptography.MD5CryptoServiceProvider();
    System.Security.Cryptography.DESCryptoServiceProvider provider 
                                = new System.Security.Cryptography.DESCryptoServiceProvider();

    provider.Mode = System.Security.Cryptography.CipherMode.CBC;

    System.Security.Cryptography.ICryptoTransform transform 
                                = provider.CreateEncryptor(keyBytes, keyBytes);
    System.Security.Cryptography.CryptoStreamMode mode 
                                = System.Security.Cryptography.CryptoStreamMode.Write;



    System.IO.MemoryStream memStream = new System.IO.MemoryStream();
    System.Security.Cryptography.CryptoStream cryptoStream 
                                = new System.Security.Cryptography.CryptoStream(memStream, transform, mode);
    cryptoStream.Write(phraseBytes, 0, phraseBytes.Length);
    cryptoStream.FlushFinalBlock();

    byte[] encryptedMessageBytes = new byte[memStream.Length];
    memStream.Position = 0;
    memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);

    encrypted = System.Convert.ToBase64String(encryptedMessageBytes);

    return (encrypted);
} // private static string EncryptDES(string phrase, string key) { }

然后在Main中这样调用:

SimpleEncryption.EncryptDES("A message regarding some secure 512-bit  encryption", "AnUltimatelyVeryVeryLongPassword");

当用户输入一个随机数的字符串长度(无论是大于还是小于8个字符)时,密码异常总是发生在这一行:

System.Security.Cryptography.ICryptoTransform transform = provider.CreateEncryptor(keyBytes, keyBytes);

它说 Specified key is not a valid size for this algorithm.

删除部分 key 以适应 8 个字符的长度(有或没有散列)似乎不是一个安全的解决方案(可能有很高的冲突率)。

如何使用用户输入的字符串实现 DES(而非 3DES)?

最佳答案

您需要根据用户的密码生成一个散列,并且仅使用 8 个字节作为您的 key 。

var fullHash = hashMD5Provider.ComputeHash(System.Text.Encoding.ASCII.GetBytes(key));
var keyBytes = new byte[8];
Array.Copy(fullHash , keyBytes, 8);

您的问题表达了对因丢弃部分哈希而导致的哈希冲突的担忧;是的,这确实会增加风险,但是(假设您的散列算法很好)您的情况不会比您仅使用仅产生 8 个字节的散列算法更糟。一个好的哈希算法应该是熵分布均匀。

关于c# - 使用用户输入密码使用 DES 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40613557/

相关文章:

c# - 如何将 Xamarin.Forms 条目绑定(bind)到非字符串类型,例如 Decimal

java - 用java加密数据库用户名和密码?

c# - 编码/解码 RealVNC 密码

戈朗 : How do I encrypt plain text that is 5 characters long with DES and CBC?

java - 解密(使用 PHP)Java 加密(PBEWithMD5AndDES)

c# - 从头开始创建 DSP 系统

c# - Nuget:如何使用 packages.config 重新创建我的包目录

android - sqlcipher_export 没有导出我的表

c# - 从 List 或 Collection 继承

c++ - srand 导致我的程序卡住