Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid length for a Base-64 char array

Tags:

c#

base64

I'm getting a "Invalid length for a Base-64 char array." inside of the IF(){...} are variations i have tried to get it to work. it fails in the first line without calling decrypt(...) proving it's not that functions problem. i get the same error inside with the first decrypt(...) call. the last one using the encoding.ascii... will get me inside the function, but then it fails inside the function. I'm getting the proper encrypted info from the database to string SSnum. it's value is: 4+mFeTp3tPF

try
{
    string SSnum = dr.GetString(dr.GetOrdinal("Social Security"));
    if (isEncrypted)
    {
      byte[] temp = Convert.FromBase64String(SSnum);
      //SSnum = decrypt(Convert.FromBase64String(SSnum), Key, IV);
      //SSnum = decrypt(Encoding.ASCII.GetBytes(SSnum), Key, IV);
    }
    txt_Social_Security.Text = SSnum;
}
catch { txt_Social_Security.Text = ""; }

I've been told to use the Convert.FromBase64String() and not the ASCII method...so why is it failing, how can i fix it?

like image 535
dave k Avatar asked Feb 01 '11 19:02

dave k


People also ask

How do you solve invalid length for a Base64 char array or string?

Solution for the “Invalid length for a Base-64 char array or string” error. Implement the code block below to check the string length and add padding characters if needed: int mod4 = encryptedtext. Length % 4; if (mod4 > 0 ) { encryptedtext += new string('=', 4 - mod4); } byte[] encryptedBytes = Convert.

What characters are invalid in Base64?

The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'. % is not allowed in base64 encoding. Save this answer.

What is the length of Base64?

BASE64 characters are 6 bits in length. They are formed by taking a block of three octets to form a 24-bit string, which is converted into four BASE64 characters.

Is there a limit to Base64 encoding?

Encode files to Base64 formatThe maximum file size is 192MB.


1 Answers

Base64 data length should be multiple of 4 and with padding char '=' You can change your data as valid base64 data.

string dummyData = imgData.Trim().Replace(" ", "+");
if (dummyData.Length % 4 > 0)
dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
byte[] byteArray = Convert.FromBase64String(dummyData); 

https://stackoverflow.com/a/9301545/2024022

This will help you , try once. Thanks suribabu.

like image 154
surbob Avatar answered Oct 29 '22 20:10

surbob