c# - 无法解密不以“=”结尾的文本
问题描述
我可以很好地加密。但是,如果一个加密的字符串最后没有以等号字母“=”结尾,那么它就不能正确解密,我得到一个空字符串(或者看起来如此)。
什么有效:
+FmU/RQ5jP86j7F6bPjddA==
YQXBLjwEXEGgYz8xnF10O9QqO/vj5DI8PpZZCvfhG1RGHAYumtWrAEBfdSSOkF79vzVCSQ+ejO3uMIDSmY43bw==
什么不起作用:
xnyfqPsvrEOK8AoQz2p7AGFHoHncZ/wB/R3qr+scts6nLI2xauWnbmYsXsU3iMoT
加密功能:
public string EncryptionKey = "abc123";
public string encrypt(string input)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(input);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
input = Convert.ToBase64String(ms.ToArray());
}
}
return input;
}
下面是解密函数:
public string decrypt(string cipherText)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
return Encoding.Unicode.GetString(ms.ToArray());
}
}
}
知道如何解决这个问题吗?
编辑:添加加密功能
编辑2:
这就是我调用加密函数的方式(在我通过 socket.io 发送字符串之前)
ASCIIEncoding aEncoding = new ASCIIEncoding();
byte[] sendMsg = new byte[1500];
sendMsg = aEncoding.GetBytes((encrypt(txtMsg.Text)));
解决方案
我不会给你完整的答案,也不会做任何密码学讲座,因为它是一个巨大的话题。您的问题的答案很简单-只要您使用Convert.FromBase64String
函数,最后没有“=”或“==”字符就无法工作,因为这些字符是这种编码的特征。“输出填充”部分中此链接下的更多信息:Wikipedia 上的 Base64
结论:如果加密的字符串带有提到的字符,则没有它就无法解密。
推荐阅读
- java - Discord JDA EmbedMessage 个人资料链接
- c# - 我应该为“类型”使用哪个关键字
- javascript - 当在其他jsp页面中包含公共jsp并且在同一页面中包含js时,公共jsp中的js文件不起作用
- python - 如何在不使用 exec() 的情况下重写它?
- bash - Bash 脚本 - 输入多个文件以运行
- odoo - menuitem 标签中的序列属性是什么?
- twitter-bootstrap - 推特图片未显示,robot.txt 允许访问图片文件夹
- date - 从 Hive SQL 中的日期减去工作日
- php - Phpmyadmin 显示代码而不是被解释
- c++ - 清除 std::map 的 boost::pool_allocator 不会返回 VS2017 中的整个池