使用ToBase64String()加密解密密码 - 特殊字符被替换为?

时间:2013-12-24 12:38:52

标签: c# encryption

我使用以下代码加密解密文本:

public static string Encrypt(string inputText)
{
        if (string.IsNullOrEmpty(inputText))
            return string.Empty;
        else
        {
            ASCIIEncoding textConverter = new ASCIIEncoding();
            RijndaelManaged myRijndael = new RijndaelManaged();

            ICryptoTransform encryptor = myRijndael.CreateEncryptor(_key, _iV);
            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
            byte[] toEncrypt = textConverter.GetBytes(inputText);
            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();
            return Convert.ToBase64String(msEncrypt.ToArray());
        }
    }

    public static string Decrypt(string inputText)
    {
        try
        {
            if (string.IsNullOrEmpty(inputText))
                return string.Empty;
            else
            {
                inputText = inputText.Replace(" ", "+");

                byte[] encrypted = Convert.FromBase64String(inputText);
                ASCIIEncoding textConverter = new ASCIIEncoding();
                RijndaelManaged myRijndael = new RijndaelManaged();

                ICryptoTransform decryptor = myRijndael.CreateDecryptor(_key, _iV);
                MemoryStream msDecrypt = new MemoryStream(encrypted);
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                byte[] fromEncrypt = new byte[encrypted.Length];
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
                return textConverter.GetString(fromEncrypt).TrimEnd('\x0');
            }
        }
        catch (Exception ex)
        {

        }
        return string.Empty;
    }

如果我在解密后尝试加密äöü++++ 2014M ,则返回 ???++ 2014M

我可以做些什么来获取相同的文字?

谢谢,

普里亚

1 个答案:

答案 0 :(得分:3)

这是因为您使用的是ASCIIEncoding。 ASCII不支持这些字符(äöü)并用问号替换它们。

您可以改用UTF8Encoding