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

About kiranpatils

As a passionate programmer I am enjoying in this field for more than 6 years, currently leading a development team. This team is responsible for keeping high up-time and low response time of application, debugging critical performance related issues, analyzing live issue as a high priority, application version upgrade and above all developing new features on top of Sitecore. Many a times I get involved in client conversations as well for new requirement or wherever some technical or functional guidance is required. Other than that, I do enjoy working in a team and building the overall strength of team by effective knowledge sharing and guidance. Spending free time with family and friends, listening music, reading books, traveling and exploring the nature, keeps me recharged! Recognized as a Microsoft Certified Technology Specialist - Web and Windows, and a Microsoft Certified Professional Developer - Web. Enjoys helping others for solving technical issues. Writes regular posts at : http://kiranpatils.wordpress.com/ and http://sitecorebasics.wordpress.com/

28 responses to “Invalid length for a Base-64 char array+RijndaelManaged/Encryption”

  1. Jason says :

    THANK YOU!

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

  2. Rana Faisal Munir says :

    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 says :

    hi thanks for the solution

  4. Nishant says :

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

  5. Sandeep says :

    THANK YOU!

  6. Amol says :

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

  7. Harry says :

    Hi,

    Really useful information….tnx buddy.

  8. Geraldo says :

    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 says :

    this solution is very good

  10. .Net Champ says :

    THANKS!! Just saved me about 2 hours!!

  11. Mohit Bhardwaj says :

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

  12. SteelerE says :

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

  13. Himanshu says :

    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 says :

      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 says :

    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 says :

    Thankssssssssss

  16. Scott says :

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

  17. Swagat says :

    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=%2fwEPDwUKLTg0MTk0NjM3Mg9kFgJmD2QWAgIDD2QWBAIDDw8WAh4EVGV4dAUQT2N0b2JlciAyNywgMjAwOWRkAg0PZBYOAgEPDxYCHwAFTkZyb20gdGhlIENlbGVudCBCbG9nOiBQaXRuZXkgQm93ZXPigJkgUkRDIEluaXRpYXRpdmUgLSB3aGVuIHdpbGwgYmFua3MgZW5nYWdlP2RkAgMPDxYCHwAFFUZyaWRheSwgSnVseSAyNCwgMjAwOWRkAgUPDxYCHwAFFENlbGVudCAgLyAgQm9iIE1lYXJhZGQCBw8PFgIfAAXTATxhIG9uY2xpY2s9ImphdmFzY3JpcHQ6T3BlbkVtYWlsKCdGcm9tIHRoZSBDZWxlbnQgQmxvZzogUGl0bmV5IEJvd2Vz4oCZIFJEQyBJbml0aWF0aXZlIC0gd2hlbiB3aWxsIGJhbmtzIGVuZ2FnZT8nKTsiIGhyZWY9IiMiIHN0eWxlPSJjdXJzb3I6IGhhbmQ7Ij48aW1nIHNyYz0iLi4vaW1hZ2VzL2NvbW1vbi9lbWFpbC5naWYiIGFsdD0iRW1haWwgQXJ0aWNsZSIvPjwvYT5kZAIJDw8WAh8ABXhQaXRuZXkgQm93ZXMgYW5kIEphY2sgSGVucnkgJiBBc3NvY2lhdGVzIChKSEEpIGhhdmUgdGVhbWVkIHVwIHRvIG9mZmVyIHJlbW90ZSBkZXBvc2l0IGNhcHR1cmUgKFJEQykgdG8gc21hbGwgYnVzaW5lc3Nlcy5kZAILDw8WAh8ABd0IRnJvbSB0aGUgPGEgaHJlZj0iaHR0cDovL2JhbmtpbmdibG9nLmNlbGVudC5jb20vP3A9NzQ2Ij5DZWxlbnQgQmFua2luZyBCbG9nPC9hPjxicj5BdXRob3I6IEJvYiBNZWFyYTxicj48YnI%2bUGl0bmV5IEJvd2VzIGFuZCBKYWNr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hY3Qgc3VpdGFibGUgZm9yIFF1aWNrQm9va3MgdXNlcnMuLi4uPGJyPjxicj48ZGl2IGFsaWduPSJjZW50ZXIiPjxhIGhyZWY9Imh0dHA6Ly9iYW5raW5nYmxvZy5jZWxlbnQuY29tLz9wPTc0NiI%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 says :

    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 says :

    This is excelent solution………

    Thanks

  20. Zondre says :

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

  21. steve patrick says :

    Awesome! Saved me some time here – thanks!

  22. Max says :

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

  23. Ali says :

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

  24. Dhaarani Vd says :

    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 says :

    its not worked…………

  26. Vero says :

    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 328 other followers

%d bloggers like this: