I have a mini system where frontend will pass the file in base64 format to the backend. I used convert.frombase64string in order for me to convert the base64 format into byte array and used file stream to save the file into the server.
The codes are shown as below:
byte[] bytes = Convert.FromBase64String(file.Split(',')[1]);
using (var file = new FileStream("D:test.txt", FileMode.Create))
{
file.Write(bytes, 0, bytes.Length);
file.Flush();
}
var db = await _context.insertDB.FromSql("INSERT INTO blobTable (blob) VALUES ('" + bytes + "')").SingleAsync();
And this is the result that I select from blobTable.
As the return result from Convert.FromBase64String() is byte array. So that I decided to store this value into my database which is postgres with column bytea[].
The problem is that is it so weird that when I trying to
console.writeline(bytes);
The result is printed as "system.byte[]" instead of the bytes value. So that "system.byte[]" is stored into my database instead of the actual value.
Can anybody tell me how do I store the return value from convert.frombase64string() into postgres bytea[] column? Thanks you.
Related
I have two LDIF files from where I am reading values and using it for comparsion using c#
One of the attribute: value in LDIF is a base64 value, need to convert it in UTF-8 format
displayName:: Rmlyc3ROYW1lTGFzdE5hbWU=
So I thought of using string -> byte[], but I am not able to use the above displayName value as string
byte[] newbytes = Convert.FromBase64String(displayname);
string displaynamereadable = Encoding.UTF8.GetString(newbytes);
In my C# code, I am doing this to retrieve the values from the ldif file
for(Entry entry ldif.ReadEntry() ) //reads value from ldif for particular user's
{
foreach(Attr attr in entry) //here attr gives attributes of a particular user
{
if(attr.Name.Equals("displayName"))
{
string attVal = attr.Value[0].ToString(); //here the value of String attVal is system.Byte[], so not able to use it in the next line
byte[] newbytes = Convert.FromBase64String(attVal); //here it throws an error mentioned below
string displaynamereadable = Encoding.UTF8.GetString(attVal);
}
}
}
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.
I am trying to user attVal as String so that I can get the encoded UTf-8 value but its throwing an error.
I tried to use BinaryFormatter and MemoryStream as well, it worked but it inserted so many new chars with the original value.
Snapshot of BinaryFormatter:
object obj = attr.Value[0];
byte[] bytes = null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
bytes = (ms.ToArray());
}
string d = Encoding.UTF8.GetString(bytes);
So the result after encoding should be: "FirstNameLastName"
But it gives "\u0002 \u004 \u004 ...................FirstNameLastName\v"
Thanks,
Base64 was designed to send binary data through transfer channels that only support plain text, and as a result, Base64 is always ASCII text. So if attr.Value[0] is a byte array, just interpret those bytes as string using ASCII encoding:
String attVal = Encoding.ASCII.GetString(attr.Value[0] as Byte[]);
Byte[] newbytes = Convert.FromBase64String(attVal);
String displaynamereadable = Encoding.UTF8.GetString(newbytes);
Also note, your code above was feeding attVal into that final line rather than newbytes.
I'm trying to convert image to binary and then store in database. I have a code to do this and after several Google searches, most answers are like the code I have written. The error I have is that instead of seeing a binary format in my database I'm getting System.byte[] as output. I also debugged and got the same thing.
Here's part of the code
if (Upload.HasFile)
{
HttpPostedFile postedFile = Upload.PostedFile;
string filename = Path.GetFileName(postedFile.FileName);
string fileExtension = Path.GetExtension(filename);
int filesize = postedFile.ContentLength;
if (fileExtension.ToLower() == ".jpg")
{
Stream stream = postedFile.InputStream;
BinaryReader binaryreader = new BinaryReader(stream);
byte[] bytes = binaryreader.ReadBytes((int)stream.Length);
Debug.WriteLine(bytes);
}
}
The result of my debug gives System.byte[] as output.
You can convert a byte array to string for DB storage
var storedString = Convert.ToBase64String(bytes);
and get the byte array from the stored string
bytes = Convert.FromBase64String(storedString);
If you really want to use the Binary format, you can look into the SoapHexBinary class, particularly the Parse() method and Value property
I have intercepted the word "admin" using this c# code
Byte[] inputBytes = Encoding.UTF8.GetBytes(stringpassword);
SHA512 shaM = new SHA512Managed();
Byte[] hashedBytes = shaM.ComputeHash(inputBytes);
string hashedpassword = BitConverter.ToString(hashedBytes);
and got the result of this "DA-EF-49-53-B9-78-33-65-CA-D6-61-52-23-72-05-06-CC". and I encrypyt the same word "admin" using SQL stored procedure
SET #password = HASHBYTES('SHA2_512',#password);
and get this as output "ÇDËv*] ¤RùèTýÁàç¥*8_#óê±Ø“ÔrcMúÇÓN¼5Ñj·ûŠÈ"
Why is there difference between these to methods?
From the documentation of the HASHBYTES function:
Return Value
varbinary (maximum 8000 bytes)
The issue here is that you're trying to interpret arbitrary binary data (the output of HASHBYTES) as a textual value, which just won't work. In this case SQL server is trying to interpret the raw byte values as characters in whatever collation your database is using.
The standard way of representing binary data in a textual form is to convert it to a base64 representation. To do this in C# replace the last line with:
string hashedpassword = Convert.ToBase64String(hashedBytes);
Then in your SQL you can do the following to convert your hashed value to base64 (based on this SO answer):
DECLARE #hashedValue VARBINARY(8000) = HASHBYTES('SHA2_512', 'admin')
SELECT
CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
, 'VARCHAR(MAX)'
) Base64Encoding
FROM (
SELECT #hashedValue AS bin
) AS bin_sql_server_temp;
If you run this you will observe that the base64 encoded values are identical.
I have a file that contains text data and binary data. This may not be a good idea, but there's nothing I can do about it.
I know the end and start positions of the binary data.
What would be the best way to read in that binary data between those positions, make a Base64 string out of it, and then write it back to the position it was.
EDIT: The Base64-encoded string won't be same length as the binary data, so I might have to pad the Base64 string to the binary data length.
int binaryStart = 100;
int binaryEnd = 150;
//buffer to copy the remaining data to it and insert it after inserting the base64string
byte[] dataTailBuffer = null;
string base64String = null;
//get the binary data and convert it to base64string
using (System.IO.Stream fileStream = new FileStream(#"c:\Test Soap", FileMode.Open, FileAccess.Read))
{
using (System.IO.BinaryReader reader = new BinaryReader(fileStream))
{
reader.BaseStream.Seek(binaryStart, SeekOrigin.Begin);
var buffer = new byte[binaryEnd - binaryStart];
reader.Read(buffer, 0, buffer.Length);
base64String = Convert.ToBase64String(buffer);
if (reader.BaseStream.Position < reader.BaseStream.Length - 1)
{
dataTailBuffer = new byte[reader.BaseStream.Length - reader.BaseStream.Position];
reader.Read(dataTailBuffer, 0, dataTailBuffer.Length);
}
}
}
//write the new base64string at specifid location.
using (System.IO.Stream fileStream = new FileStream(#"C:\test soap", FileMode.Open, FileAccess.Write))
{
using (System.IO.BinaryWriter writer = new BinaryWriter(fileStream))
{
writer.Seek(binaryStart, SeekOrigin.Begin);
writer.Write(base64String);//writer.Write(Convert.FromBase64String(base64String));
if (dataTailBuffer != null)
{
writer.Write(dataTailBuffer, 0, dataTailBuffer.Length);
}
}
}
You'll want to use a FileStream object, and the Read(byte[], int, int) and Write(byte[], int, int) methods.
Although the point about base64 being bigger than binary is valid - you'll actually need to grab the data beyond the end point of what you want to replace, store it, write to the file with your new data, then write out the stored data after you finish.
I trust you're not trying to mod exe files to write viruses here... ;)
Clearly, writing out base-64 in the place of binary data cannot work, since the base-64 will be longer. So the question is, what do you need to do this for?
I will speculate that you have inherited this terrible binary file format, and you would like to use a text-editor to edit the textual portions of this binary file. If that is the case, then perhaps a more robust round-tripping binary-to-text-to-binary conversion is what you need.
I recommend using base-64 for the binary portions, but the rest of the file should be wrapped up in XML, or some other format that would be easy to parse and interpret. XML is good, because the parsers for it are already available in the system.
<mydoc>
<t>Original text</t>
<b fieldId="1">base-64 binary</b>
<t>Hello, world!</t>
<b fieldId="2">928h982hr98h2984hf</b>
</mydoc>
This file can be easily created from your specification, and it can be easily edited in any text editor. Then the file can be converted back into the original format. If any text intrudes into the binary fields, then it can be truncated. Likewise, text that is too short could be padded with spaces.
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);