Skip to content
March 13, 2008 / kiranpatils

Invalid length for a Base-64 char array+RijndaelManaged/Encryption

I am playing with Encryption/Decryption. and its good experience. Actually i have to encrypt a Guid and have to pass it in Querystring and have to get that Querystring and again have to decrypt data based on Querystring so i will get my origianal GUI.

First My Code looks like this:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace RfcDemoPwdGenerator
{
class Helper
{
private static string password = “ABC”;
private static int iterations = 1024;
private static byte[] salt = Encoding.ASCII.GetBytes(“This is My Salt value”);
/// <summary>
/// this function will take a plaintext as an arg and
/// returns ciphertext as an O/P
/// </summary>
/// <param name=”plaintext”></param>
/// <returns></returns>
public static string Encrypt(string plaintext)
{
Rfc2898DeriveBytes KeyBytes = new Rfc2898DeriveBytes(password, salt, iterations);
//The deafault iteration count is 1000
RijndaelManaged alg = new RijndaelManaged();
alg.Key = KeyBytes.GetBytes(32);
alg.IV = KeyBytes.GetBytes(16);
MemoryStream encryptStream = new MemoryStream();
//Stream to write
CryptoStream encrypt = new CryptoStream(encryptStream, alg.CreateEncryptor(), CryptoStreamMode.Write);
//convert plain text to byte array
byte[] data = Encoding.UTF8.GetBytes(plaintext);
encrypt.Write(data, 0, data.Length); //data to encrypt,start,stop
encrypt.FlushFinalBlock();//Clear buffer
encrypt.Close();
return Convert.ToBase64String(encryptStream.ToArray());//return encrypted data
}

/// <summary>
/// this function will take a ciphertext as an arg and
/// returns plaintext as an O/P
/// </summary>
/// <param name=”plaintext”></param>
/// <returns></returns>
public static string Decrypt(string ciphertext)
{
Rfc2898DeriveBytes KeyBytes = new Rfc2898DeriveBytes(password, salt, iterations);
//The deafault iteration count is 1000
RijndaelManaged alg = new RijndaelManaged();
alg.Key = KeyBytes.GetBytes(32);
alg.IV = KeyBytes.GetBytes(16);
MemoryStream decryptStream = new MemoryStream();
//Stream to read
CryptoStream decrypt = new CryptoStream(decryptStream, alg.CreateDecryptor(), CryptoStreamMode.Write);
//convert plain text to byte array
byte[] data = Convert.FromBase64String(ciphertext); //This guy was throwing an error Invalid length for a Base-64 char array
decrypt.Write(data, 0, data.Length); //data to encrypt,start,stop
decrypt.Flush();
decrypt.Close();
return Encoding.UTF8.GetString(decryptStream.ToArray());//return PlainText
}
}
}

Solution

Why this Error?

Sometime it works fine and sometime it fails. It made me frustrated..googled it too..then also :(.

so started noting down Plaintext,URL String,Cipher text and at last got the solution and root of problem. getting excited to know it..here it is…

*********THE SOLUTION**********
Plain Text[My guid] = 72e3f882-9e0e-434f-bf51-28cffc1903c1
Cipher TEXT[generatd by my Encrypt block] = 5NGETiEwyYy3F+P+QnzkRUeB5l7xUTRJuhhGZmFwi5WxCfeo3+kCvTs0z9s+CnZW
Querystring[encrypted guid] = 5NGETiEwyYy3F P QnzkRUeB5l7xUTRJuhhGZmFwi5WxCfeo3 kCvTs0z9s CnZW

Have you seen the change in Querystring???

My Cipher contains “+” and when i pass it in Querystring it ” ” it passes[space]…

That’s the solution dude….

so for solving it just have to change the following block of Decrypt string

byte[] data = Convert.FromBase64String(ciphertext); //OLD ONE

byte[] data = Convert.FromBase64String(ciphertext.Replace(” “,”+”)); //NEW ONE
Hope it wiill save your time which i had wasted/invested…

Happy Encrypting/Decrypting!!!

Resource: http://blogs.msdn.com/shawnfa/archive/2005/11/10/491431.aspx

About these ads

28 Comments

Leave a Comment
  1. Jason / Mar 15 2008 2:22 am

    THANK YOU!

    I’ve been trying to figure this out all day. Worled like a charm!

  2. Rana Faisal Munir / Aug 6 2008 11:06 am

    Hi,

    Thanks a lot. I facing this problem and try my best, but no solutions found. You give the exact solution that solve my problem. I am very thankful and pray for you.

    Thanks
    Rana Faisal Munir

  3. Nishant / Sep 11 2008 12:10 pm

    hi thanks for the solution

  4. Nishant / Sep 11 2008 12:10 pm

    byte[] getpassword = Convert.FromBase64String(data2Decrypt);

  5. Sandeep / Sep 16 2008 7:00 am

    THANK YOU!

  6. Amol / Sep 22 2008 4:26 pm

    Thats perfect…I saved so much of time…
    Thank you Kiran…and keep up the good work :)

  7. Harry / Nov 3 2008 11:33 am

    Hi,

    Really useful information….tnx buddy.

  8. Geraldo / Nov 8 2008 9:25 pm

    OH MY GODNESS!!!! Thank you very much!
    Like others, I spend all day long trying to get this thing to work. Your solution worked (I hope for all cases, not tested yet).

    Thanks again!

  9. pjavieryb / Mar 30 2009 9:09 pm

    this solution is very good

  10. .Net Champ / May 29 2009 4:15 pm

    THANKS!! Just saved me about 2 hours!!

  11. Mohit Bhardwaj / Jun 6 2009 12:51 pm

    Thanks man. I knew something is getting changed in querysting but couldn’t find it. Thanks a lot.

  12. SteelerE / Jun 19 2009 6:28 pm

    Thank you so much for this. I was losing my hair working on the same exact issue.

  13. Himanshu / Jul 7 2009 9:41 am

    Your solution is Excellent

    I love you

    U know meaning of “Hustle” “Loyalty” and “Respect”

    just in decrypt data: in RIJINDALS ALGO——
    Decrypt old=> byte[] getpassword = Convert.FromBase64String(data2Decrypt);
    Decrypt New=>byte[] getpassword = Convert.FromBase64String(data2Decrypt.Replace(” “,”+”));

    Thanks once again ,
    I was spoil my one day before

    • kiranpatils / Jul 7 2009 11:42 am

      Thanks,

      Your comments really stimulates me to do a good job!

      Thanks for boosting me :)

      Happy Programming :)

      I just know that programming should be fun :D. And when you get issue(s) like this the fun should not lost — this is the main purpose of my post(s).

      Cheers,
      Kiran Patil

  14. Arnik / Aug 19 2009 9:57 am

    thanx a lot ….i was about to deploy the solution on staging server and this error popped up……
    but wen i read through this post it just saved my time and did not made me more frustrated…………

    thanx again

  15. Yogini / Aug 27 2009 10:35 am

    Thankssssssssss

  16. Scott / Oct 4 2009 11:19 pm

    Good job. This was the same issue I was having. Thanks for saving me a few hours of grief.

  17. Swagat / Oct 27 2009 2:30 pm

    Hi All,

    I have face a same problem like above, but little twist on scenario,
    Pls see the below error report, and af anybody can give there input that would be great

    *****************************************************************
    The following application error was encountered. MESSAGE: Invalid length for a Base-64 char array.

    SOURCE: mscorlib

    FORM: __EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2fwE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yZWY9Imh0dHA6Ly9iYW5raW5nYmxvZy5jZWxlbnQuY29tLz9wPTc0NiI%2bPHU%2bPGI%2bUmVhZCB0aGUgZnVsbCBhcnRpY2xlIGF0IHRoZSBDZWxlbnQgQmFua2luZyBCbG9nIGJ5IGNsaWNraW5nIGhlcmUuPC9iPjwvdT48YnI%2bPC9hPjwvZGl2PmRkAg0PZBYEAgEPDxYCHgdWaXNpYmxlaGRkAgMPDxYCHwBlZGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFNGN0bDAwJG1haW5Db250ZW50JG5ld3NDb21tZW50Rm9ybSRyZW1lbWJlck1lQ2hlY2tCb3g%3d&__EVENTVALIDATION=3&ctl00%24searchTermBox=oDySEzKhSwVeZGa&ctl00%24mainContent%24newsCommentForm%24cUserTextBox=UBUNNa++%3ca+href%3d%22http%3a%2f%2fwvtcgfghreqm.com%2f%22%3ewvtcgfghreqm%3c%2fa%3e%2c+%5burl%3dhttp%3a%2f%2fypjyiiodmtvg.com%2f%5dypjyiiodmtvg%5b%2furl%5d%2c+%5blink%3dhttp%3a%2f%2fhaxvybcpegan.com%2f%5dhaxvybcpegan%5b%2flink%5d%2c+http%3a%2f%2fxmdjjjnyfvvj.com%2f&ctl00%24mainContent%24newsCommentForm%24cPassTextBox=&ctl00%24mainContent%24newsCommentForm%24commentTextBox=UBUNNa++%3ca+href%3d%22http%3a%2f%2fwvtcgfghreqm.com%2f%22%3ewvtcgfghreqm%3c%2fa%3e%2c+%5burl%3dhttp%3a%2f%2fypjyiiodmtvg.com%2f%5dypjyiiodmtvg%5b%2furl%5d%2c+%5blink%3dhttp%3a%2f%2fhaxvybcpegan.com%2f%5dhaxvybcpegan%5b%2flink%5d%2c+http%3a%2f%2fxmdjjjnyfvvj.com%2f&ctl00%24mainContent%24newsCommentForm%24submitCommentButton=Submit+Comment

    QUERYSTRING: aid=24700

    TARGETSITE: Byte[] FromBase64String(System.String)

    STACKTRACE: at System.Convert.FromBase64String(String s) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded()

    Server: WEB15
    Alert Time: 10/27/2009 7:59:25 AM
    ************************************************************

  18. Haresh M Ambaliya / Nov 30 2009 9:07 am

    Hi,

    Excellent solution of problem.

    Thanks, I also got the error and i have started googling and found best solution as u given.

    Thanks again.

  19. Sekhar Singara / Mar 13 2010 1:16 pm

    This is excelent solution………

    Thanks

  20. Zondre / Sep 21 2010 3:42 am

    Thank you, this fixed a problem I was sometimes having with my e-mail verification.

  21. steve patrick / Oct 29 2010 4:45 pm

    Awesome! Saved me some time here – thanks!

  22. Max / Jan 25 2011 5:08 pm

    Great solution. You definitely saved me a load of time!

    • kiranpatils / Mar 10 2011 2:58 am

      Thanks Max!

      Thanks for visiting the blog!

      Sincerely,
      Kiran Patil

  23. Ali / Jul 8 2011 5:11 pm

    Thanks for sharing, you save my time.
    That’s great

  24. Dhaarani Vd / Sep 24 2011 3:35 pm

    i am getting another error even after replacing with the new code and the error is
    String cannot be of zero length.
    Parameter name: oldValue

  25. Balva / May 4 2012 2:25 pm

    its not worked…………

  26. Vero / Oct 18 2013 7:45 pm

    Thanks a lot!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 415 other followers

%d bloggers like this: