我还在学习密码学。我试图在C#中创建一个简单的静态函数,将字符串加密到DES(使用Base64输出)。我了解到DES使用8-Byte作为关键。我希望用户输入任意长度的字符串,将其用作加密消息的密钥,然后将其转换为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.
删除密钥的部分以适合8个字符的长度(有或没有散列)似乎不是一个安全的解决方案(可能存在高速率的冲突)。
如何使用用户输入字符串实现DES(而不是3DES)?
答案 0 :(得分:0)
您需要根据用户的密码生成哈希值,并且只需8个字节即可用作密钥。
var fullHash = hashMD5Provider.ComputeHash(System.Text.Encoding.ASCII.GetBytes(key));
var keyBytes = new byte[8];
Array.Copy(fullHash , keyBytes, 8);
你的问题表达了对丢弃部分哈希的哈希冲突的担忧;是的,这肯定会增加风险,但是(假设你的哈希算法是好的)你不会比你刚刚使用只生成8个字节的哈希算法更糟糕。一个好的哈希算法应该均匀地分配熵。