rahul kadachira
rahul kadachira

Reputation: 43

Getting Error while decrypting string

I am getting an error while decrypting and encrypted string:

5duOH+Tlg5deIrWZiHoNaQ==wVxXSl9pFu6A8h14/nLdyBkDzO4xmec7PQ0cB7MHjCDqhSRum3C7I1OfqL1rEWbNonU/ayCaJS18zV7ivQQU7A==MBJzKMrrrbmc2/vBZSPDkQ==I09Kj25UO+LcmRzgoqTT2g==+Fkm9VCGplEK6eEyHyEtuEodKSbckC07M2FShu2ukCg=

Error is as follows:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

My encryption code is: public string EncryptQueryString(string inputText, string key, string salt) { byte[] plainText = Encoding.UTF8.GetBytes(inputText);

    using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
    {
        PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));
        using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(plainText, 0, plainText.Length);
            cryptoStream.FlushFinalBlock();
            string base64 = Convert.ToBase64String(memoryStream.ToArray());

            // Generate a string that won't get screwed up when passed as a query string.
            string urlEncoded = HttpUtility.UrlEncode(base64);
            return urlEncoded;
        }
    }
}

Decryption:

public string DecryptQueryString(string inputText, string key, string salt)
{
    byte[] encryptedData = Convert.FromBase64String(inputText);
    PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));

    using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
    using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
    using (MemoryStream memoryStream = new MemoryStream(encryptedData))
    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
    {
        byte[] plainText = new byte[encryptedData.Length];
        cryptoStream.Read(plainText, 0, plainText.Length);
        string utf8 = Encoding.UTF8.GetString(plainText);
        return utf8;
    }
}

Upvotes: 1

Views: 1387

Answers (1)

Peter B
Peter B

Reputation: 24280

Base64 padding consists of = or ==, and so it looks like multiple Base64 strings where appended together somehow. You'll have to find where they all originally ended, split them there, and try again.

Note that Base64 strings do not always have padding, only when it is needed, so there may even need to be breaks in places that you cannot see here.

Upvotes: 2

Related Questions