2

I am encryption/decryption some plain text using following code.

private static string EncryptionKey = "@#$%^&*()2343";    
private static byte[] Salt = Encoding.ASCII.GetBytes(EncryptionKey.Length.ToString()); 

public static string EncryptIt(string Input)    
{    
    RijndaelManaged Cipher = new RijndaelManaged();    
    byte[] TextByteArray = Encoding.Unicode.GetBytes(Input);    
    PasswordDeriveBytes Key = new PasswordDeriveBytes(EncryptionKey, Salt);    

    using (ICryptoTransform Transform = Cipher.CreateEncryptor(Key.GetBytes(32), Key.GetBytes(16)))    
    {        
        using (MemoryStream MS = new MemoryStream())    
        {    
            using (CryptoStream CS = new CryptoStream(MS, Transform, CryptoStreamMode.Write))    
            {    
                CS.Write(TextByteArray, 0, TextByteArray.Length);    
                CS.FlushFinalBlock();    
                return Convert.ToBase64String(MS.ToArray());    
            }    
        }    
    }    
}    

public static string DecryptIt(string Input)    
{    
    RijndaelManaged Cipher = new RijndaelManaged();    
    byte[] EncryptedByteArray = Convert.FromBase64String(Input);    
    PasswordDeriveBytes Key = new PasswordDeriveBytes(EncryptionKey, Salt);    

    using (ICryptoTransform Transform = Cipher.CreateDecryptor(Key.GetBytes(32), Key.GetBytes(16)))    
    {    
        using (MemoryStream MS = new MemoryStream(EncryptedByteArray))    
        {    
            using (CryptoStream cryptoStream = new CryptoStream(MS, Transform, CryptoStreamMode.Read))    
            {    
                byte[] TransformedText = new byte[EncryptedByteArray.Length];    
                int Count = cryptoStream.Read(TransformedText, 0, TransformedText.Length);    
                return Encoding.Unicode.GetString(TransformedText, 0, Count);    
            }    
        }    
    }    
}    

In most of the cases, this code works fine. However in some cases when I try to decrypt the encrypted text, I get following exception when byte[] EncryptedByteArray = Convert.FromBase64String(Input) is called in DecryptIt methods.

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.

Any idea what could be causing this exception. What I am finding more puzzling is that why this excpetion is not thrown on every cases and only few cases.

EDIT : Sample Input to DecryptIt method that throws exception is below. Please note that I have changed the value of EncryptionKey variable in my sample above.

oaOQ6qWWDwWby3C04N7HJAiqQgILBifqdHq4OQ5KDDRA3F2ZlBITu31a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+xHz/S1a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+oz/eR9OzXn+3Lepo0tRqH5BsfvEtJ/IcqRu3gJiIBTMAM0TmVxa2EZSj2mn6jZlgvlOEFCWzNKS3R9OzXn+In1br14venJmpApXyt930khz35UE5BtWn3Fq7jyer6mY2l60P/cI4z

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
palm snow
  • 2,392
  • 4
  • 29
  • 49
  • 3
    Please post what the value of `Input` is when this exception is thrown. – Gromer Oct 01 '12 at 18:19
  • Input is an email address and a Guid value with some fixed text. – palm snow Oct 01 '12 at 18:23
  • 1
    @palmsnow: Well that's not a base64 value, is it? The value of `Input` should be the result of calling `EncryptIt`, which *is* a base64 value. – Jon Skeet Oct 01 '12 at 18:23
  • @JonSkeet, PalmSnow - that's the other Input. – H H Oct 01 '12 at 18:26
  • If the error only sometimes happens then that points to an error in transport/storage between EncryptIt and DecryptIt. – H H Oct 01 '12 at 18:27
  • @Jon: That's the input to EncryptIt method. The input to DecryptIt that throws an exception is oaOQ6qWWDwWby3C04N7HJAiqQgILBifqdHq4OQ5KDDRA3F2ZlBITu3 1a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+xHz/S 1a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+oz/e R9OzXn+3Lepo0tRqH5BsfvEtJ/IcqRu3gJiIBTMAM0TmVxa2EZSj2mn6jZlgvlOEFCWzNKS3 R9OzXn+In1b r14venJmpApXyt930khz35UE5BtWn3Fq7jyer6mY2l60P/cI4z – palm snow Oct 01 '12 at 18:27
  • @palmsnow - add that sample to the question. Important info shouldn't be in a comment, and the formatting options are limited. – H H Oct 01 '12 at 18:29
  • @Henk: The ecrypted text is sent via email in a http link. DecryptIt is called when user click on that link. What could be wrong with this transport mechanism? Remember its works fine for most of cases. – palm snow Oct 01 '12 at 18:29
  • @palmsnow: Does `Input` have line breaks in it, or other whitespace? It would really help if we knew the *exact* value. – Jon Skeet Oct 01 '12 at 18:32
  • @Jon: I copied exact one that is throwing excpetion. It shouldn't have any whitespaces because this encrypted text is created using Base64 (that shouldn't have any whitespaces). Am i missing anything? – palm snow Oct 01 '12 at 18:33
  • @palmsnow: The trouble is that you've included it in a comma, which makes it impossible to know what's really there. You *appear* to have spaces in it - look just before "R9Oz" for example. (In particular, you *want* it to be just the result of a base64 encoding call, but it's clearly not or you wouldn't get an exception...) – Jon Skeet Oct 01 '12 at 18:35
  • It may be caused by copy and paste here. Because I have this text in notepad++ with "Show All Characters" On and it does not show any CR or LF in there – palm snow Oct 01 '12 at 18:38
  • The different line lengths in your base64 data and the long repeated substrings suggest that something is mangling the buffer. Like it says in the error message, you should have a multiple of four characters; usually, if base64 ends up an uneven length, you pad at the end with `=` characters, but this looks more thoroughly mangled than that. – tripleee Oct 01 '12 at 18:38
  • Whitespace (space, tab newline) is ignored in a Base64 string. – H H Oct 01 '12 at 18:41
  • Are you concatenating the results from `EncryptIt` anywhere? Concatenated Base64 strings may not be Base64 strings. – Dour High Arch Oct 01 '12 at 18:49
  • @HenkHolterman: yes, whitespace is ignored, but the fact that you have erratic whitespace strongly suggests that something has been messing with the data. – tripleee Oct 03 '12 at 16:28
  • See also https://stackoverflow.com/questions/15114044/ – surfmuggle Mar 23 '22 at 14:39

1 Answers1

1

Your sample deconverts perfectly with 2 extra '=' at the end.
So somewhere they are lost in transport.

The ecrypted text is sent via email in a http link.

So that involves both URL and HTML encoding? Plenty of room for an error.

Run a test with a small string ending in ==.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Any suggestion on what could be done when sending this encrypted string as http link querystring. The whole text is send in an email from a win-form application? – palm snow Oct 01 '12 at 18:42
  • I guess I can set BodyEncoding of MailMessage to System.Text.Encoding.UTF8. You think that will be enough? – palm snow Oct 01 '12 at 18:48
  • I think you should show your code around `HttpUtility.UrlEncode()`, or how otherwise you create that URL. – H H Oct 01 '12 at 18:51
  • As of now, its done using concatenating string via string.Format. I guess this may be it? :) – palm snow Oct 01 '12 at 18:55
  • Yes, URLs don't like `=` in their queries. But `/` shouldn't be cool either. You need proper encoding and decoding. URL only, I don't think HTML is involved. – H H Oct 01 '12 at 18:58