首页 > 解决方案 > 无法解密不以“=”结尾的文本

问题描述

我可以很好地加密。但是,如果一个加密的字符串最后没有以等号字母“=”结尾,那么它就不能正确解密,我得到一个空字符串(或者看起来如此)。

什么有效:

+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)));

标签: c#encryptionbase64

解决方案


我不会给你完整的答案,也不会做任何密码学讲座,因为它是一个巨大的话题。您的问题的答案很简单-只要您使用Convert.FromBase64String函数,最后没有“=”或“==”字符就无法工作,因为这些字符是这种编码的特征。“输出填充”部分中此链接下的更多信息:Wikipedia 上的 Base64 结论:如果加密的字符串带有提到的字符,则没有它就无法解密。


推荐阅读