I have this image represented as base64 string which I have pasted over here:
https://paste.ubuntu.com/23343680/
there is an image inside it. I am calling a
Convert.FromBase64String
and it gives me
{"Invalid length for a Base-64 char array or string."}
Now I have used this website http://codebeautify.org/base64-to-image-converter to paste the same string and it renders the image in the data just fine.
What is it that I am doing wrong here, I need to get a byte[] which I will make the image from but I cant.
thanks.
You have to append = until the length is divisible by 4. Only that is a valid base64 string.
This code will do:
string s = "yourVeryLongBase64String";
if ((s.Length % 4) > 0)
{
int diff = 4 - (s.Length % 4);
s = s.PadRight(s.Length + diff, '=');
}
byte[] b = Convert.FromBase64String(s);
string str = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCAHgAoADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaan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/9EZ/8uDT/wD5Io/4dy/tp/8ARGf/AC4NP/8Akiv1HooA/Lj/AIdy/tp/9EZ/8uDT/wD5Io/4dy/tp/8ARGf/AC4NP/8Akiv1HooA/Lj/AIdy/tp/9EZ/8uDT/wD5Io/4dy/tp/8ARGf/AC4NP/8Akiv1HooA8S/4eM/sWf8ARZ//AC39Q/8Akej/AIeM/sWf9Fn/APLf1D/5Hr8uKKAP1H/4eM/sWf8ARZ//AC39Q/8Akej/AIeM/sWf9Fn/APLf1D/5Hr8uKKAP1H/4eM/sWf8ARZ//AC39Q/8Akej/AIeM/sWf9Fn/APLf1D/5Hr8uKKAP1H/4eM/sWf8ARZ//AC39Q/8Akej/AIeM/sWf9Fn/APLf1D/5Hr8uKKAPbf8Ah3L+2n/0Rn/y4NP/APkij/h3L+2n/wBEZ/8ALg0//wCSK/UeigD8uP8Ah3L+2n/0Rn/y4NP/APkij/h3L+2n/wBEZ/8ALg0//wCSK/UeigD8uP8Ah3L+2n/0Rn/y4NP/APkij/h3L+2n/wBEZ/8ALg0//wCSK/UeigD8uP8Ah3L+2n/0Rn/y4NP/APkij/h3L+2n/wBEZ/8ALg0//wCSK/UeigDxL/h4z+xZ/wBFn/8ALf1D/wCR6P8Ah4z+xZ/0Wf8A8t/UP/kevy4ooAKKKKACiiigAooooA/bSiiigAooooAKKKKACiiigD8S6KKKACiiigAooooAKKKKAP20ooooAKKKKACiiigAooooA/EuiiigAooooAKKKKACiiigD9tKKKKACiiigAooooAKKKKAPxLooooAKKKKACiiigAooooA/bSiiigAooooAKKKKACiiigD8S6KKKACiiigAooooAKKKKAP20ooooAKKKKACiiigAooooA/EuiiigAooooAKKKKACiiigD9tKKKKACiiigAooooAKKKKAPxLooooAKKKKACiiigAooooA===";
byte[] arr = Convert.FromBase64String(str);
Add == at the end of string. it will work. the input you are passing is not valid base64 value
Related
I have a base64 jpeg like so: data:image/jpeg;base64 and I am trying to convert it to a MemoryStream so I can upload it to OneDrive....Here is what I got so far:
byte[] frontBytes = Convert.FromBase64String(user.FrontLicense);
using (MemoryStream frontMS = new MemoryStream(frontBytes))
{
await graphClient.Me.Drive.Items[newFolder.Id].ItemWithPath("FrontLicense.jpeg").Content.Request().PutAsync<DriveItem>(frontMS);
}
But I get this error:
The input is not a valid Base-64 string as it contains a non-base 64
character, more than two padding characters, or an illegal character
among the padding characters.
On this line:
byte[] frontBytes = Convert.FromBase64String(user.FrontLicense);
This is what user.FrontLicense looks like:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoM.....
What am I doing wrong?
The part at the start - data:image/jpeg;base64, - isn't part of the base64 data. So you need to remove that first:
const string Base64ImagePrefix = "data:image/jpeg;base64,"
...
if (user.FrontLicense.StartsWith(Base64ImagePrefix))
{
string base64 = user.FromLicense.Substring(Base64ImagePrefix.Length);
byte[] data = Convert.FromBase64String(base64);
// Use the data
}
else
{
// It didn't advertise itself as a base64 data image. What do you want to do?
}
So, I have a string that is actually UTF encoded characters with the ASCII representation codes stripped out:
"537465616d6c696e6564"
This would be represented in ASCII encoded UTF as \x53\x74\x65 [...]
I've tried to Regexp replace in \x at the correct positions, byte encoding it and reading it back as UTF, but to no avail.
What's the most effective way of turning the ASCII string into readable UTF in C#?
So what I understand you have a string "537465616d6c696e6564" that actually means char[] chars = { '\x53', '\x74', ... }.
First convert this string to array of bytes How can I convert a hex string to a byte array?
For your convenience:
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
Then there are many UTF encodings (UTF-8, UTF-16), C# internally uses UTF-16 (actually subset of it), so I assume that you want UTF-16 string:
string str = System.Text.Encoding.Unicode.GetString(array);
If you get incorrect characters after decoding you may also try UTF-8 encoding (just in case if you don't know exact encoding, Encoding.UTF8).
I don't know much about string encodings, but assuming that your original string is the hex representation of a series of bytes, you could do something like this:
class Program
{
private const string encoded = "537465616d6c696e6564";
static void Main(string[] args)
{
byte[] bytes = StringToByteArray(encoded);
string text = Encoding.ASCII.GetString(bytes);
Console.WriteLine(text);
Console.ReadKey();
}
// From https://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
If you later wanted to encode the result as UTF8, you could then use:
Encoding.UTF8.GetBytes(text);
I've taken one implementation of the StringToByteArray conversion but there are many. If performance is important, you may want to choose a more efficient one. See the links below for more info.
On byte to string conversion (some interesting discussions on performance):
How do you convert Byte Array to Hexadecimal String, and vice versa?
How can I convert a hex string to a byte array?
On strings in .NET
Determine a string's encoding in C#
http://csharpindepth.com/Articles/General/Strings.aspx
I'm trying to encode some strings back and forth from base-64 string and I'm having truble to get the right result.
string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);
if (text == base64Encoded) //If the new encoded string is equal to its original value
return base64Encoded;
I have tried my ways to do this and I don't seem to get the right result. I have tried both with System.Text.Encoding.Unicode and System.Text.Encoding.UTF8
What could be the problem? Does anyone have a proper solution?
string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);
You are double encoding the string. You begin with a base64 string, get the bytes, and then encode it again. If you want to compare you will need to begin with the original string.
If text is a base-64 string, then you are doing it backwards:
byte[] raw = Convert.FromBase64String(text); // unpack the base-64 to a blob
string s = Encoding.UTF8.GetString(raw); // assume the blob is UTF-8, and
// decode to a string
which will get you it as a string. Note, though, that this scenario is only useful for representing unicode text in an ascii format. Normally you wouldn't base-64 encode it if the original contents are string.
Convert whatever it is that you need in Base64 into a Byte array then use the FromBase64String and ToBase64String to convert to and from Base64:
Byte[] buffer = Convert.FromBase64String(myBase64String1);
myBase64String2 = Convert.ToBase64String(buffer);
myBase64String1 will be equal to myBase64String2. You will need to use other methods to get your data type into a Byte array and the reverse to get your data type back. I have used this to convert the content of a class into a byte array and then to Base64 string and write the string to the filesystem. Later I read it back into a class instance by reversing the process.
You have the encoding code correctly laid out. To confirm whether the base64-encoded string is correct, you can try decoding it and comparing the decoded contents to the original:
var decodedBytes = Convert.FromBase64String(base64encoded);
var compareText = System.Text.Encoding.ASCII.GetString(decodedText);
if (text == compareText)
{
// carry on...
return base64encoded;
}
I have a string that represents a byte
string s = "\x00af";
I write this string to a file so the file contains the literal "\x00af" and not the byte it represents, later I read this string from the file, how can I now treat this string as byte again (and not the literal)?
Here is a sample code:
public static void StringAndBytes()
{
string s = "\x00af";
byte[] b = Encoding.ASCII.GetBytes(s);
// Length would be 1
Console.WriteLine(b.Length);
// Write this to a file as literal
StreamWriter sw = new StreamWriter("c:\\temp\\MyTry.txt");
sw.WriteLine("\\x00af");
sw.Close();
// Read it from the file
StreamReader sr = new StreamReader("c:\\temp\\MyTry.txt");
s = sr.ReadLine();
sr.Close();
// Get the bytes and Length would be 6, as it treat the string as string
// and not the byte it represents
b = Encoding.ASCII.GetBytes(s);
Console.WriteLine(b.Length);
}
Any idea on how I convert the string from being a text to the string representing a byte? Thx!
Is it a requirement for the file content to have the string literal? If no, then you might want to write the byte[] b array directly to the file. That way when you read it, it is exactly, what you wrote.
byte[] b = Encoding.UTF32.GetBytes(s);
File.WriteAllBytes ("c:\\temp\\MyTry.txt", b);
b = File.ReadAllBytes ("c:\\temp\\MyTry.txt");
s = Encoding.UTF32.GetString (b);
If you need the file content to have the string literal, while being able to convert it to the original text written, you will have to choose the right encoding. I believe UTF32 to be the best.
b = new byte[4];
b[0] = Byte.Parse(s.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
string v = Encoding.UTF32.GetString(b);
string w = "\x00af";
if (v != w)
MessageBox.Show("Diff [" + w + "] = [" + v + "] ");
else
MessageBox.Show("Same");
Not sure if I understand the question correctly, but you're not writing the string s to the file. You have an extra \ in your WriteLine statement! WriteLine("\\x00af") writes the characters \, x, 0, 0, a and f, since the first \ acts as an escape to the second one ...
Did you mean
sw.WriteLine("\x00af");
or
sw.WriteLine(s);
instead? This works as expected in my tests.
Use the Encoding.ASCII.GetString(byte[]) method. It is also available from all the others encoding. Make sure you always use the same encoding to decode the byte[] as you used to encode it or you won't get the same value every time.
Here's an example.
Just parse a string representing each byte:
Byte b = Byte.Parse(s);
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?
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.
it's value is: 4+mFeTp3tPF
You are receiving this error because that value, 4+mFeTp3tPF, is in fact not valid Base64.
Is it possible you are simply missing the required padding character, as so 4+mFeTp3tPF=?
Are you certain that you have a Base64 string? Base64 is a means of encoding binary data into a string while only using standard 7-bit ASCII characters. It's not a string encoding like ASCII and has some control bytes present. You have a Base64 string if you're using Convert.ToBase64String to obtain the value (which, if you're trying to store binary data as a string, is your best bet)
Judging by your error (and your example data), I'm assuming that you do not have a Base64 string. If you need to store binary data in the database, you can either create a column using a binary type or encode the string into Base64 by using Convert.ToBase64String.
byte[] inputData = ...;
string base64String = Convert.ToBase64String(inputData);
byte[] outputData = Convert.FromBase64String(base64String);
Here, outputData should contain the same data as inputData.
If what you have is just an ASCII-encoded string, then your original practice of using System.Text.Encoding.ASCII.GetBytes() is correct, but you should change this to use a Base64 string if you can.
Are you sure that string 4+mFeTp3tPF is well-formed Base64 string?
I've tried some online services - no one could convert it.
replace
byte[] temp = Convert.FromBase64String(SSnum);
to this
var temp = UTF8Encoding.UTF8.GetBytes(SSnum);