输入不是有效的Base64字符串,因为它在C#中包含非基本64字符?

时间:2014-01-09 12:05:01

标签: c# json wcf encryption

我在WCF Web服务中使用以下方法加密和解密请求和响应:

public static string Decrypt(string textToDecrypt, string key)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize = 0x80;
            rijndaelCipher.BlockSize = 0x80;

            string decodedUrl = HttpUtility.UrlDecode(textToDecrypt);
            byte[] encryptedData = Convert.FromBase64String(decodedUrl);
            byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[0x10];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
            {
                len = keyBytes.Length;
            }
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = keyBytes;
            byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return encoding.GetString(plainText);
        }


       public static string Encrypt(string textToEncrypt, string key)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize = 0x80;
            rijndaelCipher.BlockSize = 0x80;
            byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[0x10];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
            {
                len = keyBytes.Length;
            }
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = keyBytes;
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
            return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
        }

通过使用方法数据加密和解密成功。之后,我成功加密JSON对象,但在解密时面临问题   我正在使用以下数据:

用于加密

Encrypt("{\"password\":\"Password123\",\"username\":\"Jhon.Trrot\"}", "demo")
解密

Decrypt(encString, "demo");

当我删除:,时,它工作得很好但:,收到此错误:

The server encountered an error processing the request. The exception message is 'The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. '.

1 个答案:

答案 0 :(得分:2)

您忘记在加密方法中对编码您的base 64输出进行URL。