我正在使用以下方法在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. '.

最佳答案

您忘记了使用加密方法对base 64输出进行URL编码。

关于c# - 输入不是有效的Base64字符串,因为它在C#中包含非基数64字符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21019757/

10-09 07:41