13

Q: I face the following big problem :

from time to another i find the following exception:

Invalid length for a Base-64 char array

I use encryption and decryption:

public static string Encrypt(string text)
        {

            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] byteArray = Encoding.UTF8.GetBytes(text);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream,des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();
                return Convert.ToBase64String(memoryStream.ToArray());
            }

            catch (Exception ex)
            {
              string message =  ex.Message;
            }

            return string.Empty;
        }



        public static string Decrypt(string text)
        {
            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                text = text.Replace(" ", "+")
                Byte[] byteArray = Convert.FromBase64String(text);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }

            catch (Exception ex)
            {
                string message = ex.Message;

            } 

i read many articles about the problem some posts talking about the solution is:

text = text.Replace(" ", "+") and this not fixes my problem at all

my string is :3DZF/NZpp0yuQ=3D please i need help to fix this problem.

EDIT

  • If there are any modifications or enhancements to this class to make it work better or more secure or avoid any possible problems like this , i will be grateful.
  • If there are alternating classes instead of this,more secure and doesn't make these problems , I will be grateful.
  • I use this class in a small application used to verifying mails.

EDIT:

Decoding the querystring values is done already when it's parsed into the Request.

https://stackoverflow.com/a/10879400/418343

Community
  • 1
  • 1
Anyname Donotcare
  • 11,113
  • 66
  • 219
  • 392
  • 2
    A common problem is incorrectly stripping the padding (trailing equal signs) from the end of a string. In your case "=3d" is likely supposed to be simply "=" or perhaps "==" – EricLaw Dec 29 '10 at 15:15
  • 2
    Doesn't answer your question, but this is a really bad way of encrypting - sounds like you are doing the same thing as gawker. You are only using the first 8 characters as a key, and using DES (an outdated encryption standard) See http://www.codinghorror.com/blog/2010/12/the-dirty-truth-about-web-passwords.html – Nick Fortescue Dec 29 '10 at 15:18
  • A side-note: `Encoding.UTF8.GetBytes` is a very bad and unsafe way to get a Key from a password. – H H Dec 29 '10 at 15:22
  • 1
    Looks like @EricLaw is correct in that it should be `==`. Is this base64 string gathered from a query string? `%3D` is the URL-encoded form of `=`, so it looks like your problem lies with URL encoding – John Rasch Dec 29 '10 at 15:23
  • then what are the alternates to this class.. or how to fix this problem – Anyname Donotcare Dec 29 '10 at 15:30
  • is there an alternating class for encryption and decryption and doesn't make these errors. – Anyname Donotcare Dec 29 '10 at 15:33
  • 1
    Take a look at http://stackoverflow.com/questions/2925729/invalid-length-for-a-base-64-char-array. For Base64, the value should be multiples of 4 – LCJ Feb 19 '13 at 07:29

2 Answers2

19

To solve the problems you need to fist Encode and then Decode the all ready encode-base64 string, depend from where you using it.

If for example you use it on url (or query) where probably this is the place you going to use, then you need to Encode the URL before you use it, decode the url before you get it back. The reason is that you need to avoid to mix the same characters that URL use as code character, with the encrypted characters.

Anyway here is the code that solve your problem (and I use for the same reason):

public static string encodeSTROnUrl(string thisEncode)
{
    if (null == thisEncode)
        return string.Empty;

    return HttpUtility.UrlEncode(Encrypt(thisEncode));
}


public static string decodeSTROnUrl(string thisDecode)
{
    return Decrypt(HttpUtility.UrlDecode(thisDecode));
}

ps I have the same problem, and have try as you say replace the '+' and other, but at the end this is what make it works.

Don't forget to remove the text = text.Replace(" ", "+"), and other manipulations of the encryption from your code, just encrypt and decrypt.

Aristos
  • 66,005
  • 16
  • 114
  • 150
  • the string comes from a query string..is your method still do what i wanna to do – Anyname Donotcare Dec 29 '10 at 16:13
  • sorry please i'm confused little , can u tell me where to call these methods in my code.thanks in advance – Anyname Donotcare Dec 29 '10 at 16:22
  • @just_name, The Encrypt/Decrypt function that I call is your functions. Now on your code instead you call the Encrypt/Decrypt, you call the encodeSTROnUrl/decodeSTROnUrl. – Aristos Dec 29 '10 at 16:34
  • ok thanks a lot ...i will try your method , and i hope to fix this problem indeed. – Anyname Donotcare Dec 30 '10 at 07:13
  • @just_name yes it will solve it, I use to have the same problem, and after a lot of tests I end up with this. This now work on my sites for more than 3 years with out problem. – Aristos Dec 30 '10 at 10:07
  • @Aristos: thanks alot , but please when i tried to encyrpt (7200406) i face the same exception , is this beacuse it is long number or what?? – Anyname Donotcare Feb 27 '11 at 08:13
  • 1
    @just_name no this is not a long number, actually something else must be your issue. – Aristos Feb 27 '11 at 13:26
-2
string imag = img;
imag = imag.Replace("\", "");
int c = imag.Length % 4;
if ((c) != 0)
    imag = imag.PadRight((imag.Length + (4 - c)), "=");
[] converted = Convert.FromBase64String(imag);
using (System.IO.MemoryStream vstream = new System.IO.MemoryStream(converted)) {
    return Image.FromStream(vstream);
}