xml issue incorporating byte array - c#

hello i use a form of message parsing in which i write fields into a buffered stream, and then extract a byte array repesantaition of that stream
MyMessage _message = new MyMessage("me","you",MessageType.peer_message,4252422) ;
// in the constructor String sender,String receiver,MessageType(enumaraition) m_type,Int32 id
byte [] buffer = myEncoder.encode(message) ;
now when i pass this to myDecoder it decodes it in the same metter and it works great !
how i do that is not the issue
my issue is that in some cases of misscommunicaition i need to store the byte[] array (buffer) for farther use , and i'm trying to do that in an xmlDocumant under a tag
HERE IN THE INNER TEXT IS WHERE I WOULD LIKE TO SAVE THAT ARRAY OF BYTES
ive tryed -->
utf8Encoding.Ascii.getString(buffer) which save some kind of repsantaition
but it changes values of field wich are not strings... when i take it out by using
utf8Encoding.Ascii.getBytes(packet_node.innerText) ;
1)THE QUESTION IS HOW WOULD U GO ABOUT SAVING THAT BYTE ARRAY TO A XMLNODE
2)i've also tried just writing the fields one by one in each tag
<Packet>
<sender>me</sender>
<receiver>him</receiver>
<MessageType> ..?? how would i represent a byte as a string ? </MessageType>
<Id> 4252353523 </Id> here i have no problem but i still would have to always prase the value back and forth in other uses from int to string ..
</Packet>
3) so my conclusion is to serialize the byte array to an xmldocument .. just that i don't want it to be a document but just one node in an existing document

Encode it as a base-64 string. Just remember to decode it when you read it back.
byte[] bytes = ...;
string encoded = Convert.ToBase64String(bytes);
byte[] decoded = Convert.FromBase64String(encoded);

Related

string to byte array (to string to XML) and back again

i know there are 1million questions about "string - byte array" conversion out there but none of them fit my problem.
For the installation of my software i need to save some informations from the user (serveraddress, userID, password and so on). Some of these informations need do be protected (encrypted using DPAPI). For that i have to convert the string (SecureString) to byte[]
public static byte[] StringToByte(string s)
{
return Convert.FromBase64String(s);
}
where i get my first problem. If the strings lenght is a not a multiple of 4 (s.lenght % 4 == 0) i get a "Invalid length for a Base-64 char array" error. I've read that i can (have to) add "=" to the end of the string but some of these strings may be passwords (which may contain "="). I need to store the (encrypted) data in a XML-file why i can't use Unicode encoding (i don't know why but it corrupts the XML file ... because of encoding i would suppose).
As last step i have to go back the way to get the stored data on app startup.
Does someone of you can help me solving this problem ? I don't care the output in the XML as long as it is "readable".
best regards Alex
where i get my first problem. If the strings lenght is a not a multiple of 4 (s.lenght % 4 == 0) i get a "Invalid length for a Base-64 char array" error.
That suggests that it's not base64 to start with. It sounds like you're going in the wrong direction here - base64 is used to convert binary data into text. To convert text into a binary form, you should normally just use Encoding.GetBytes:
return Encoding.UTF8.GetBytes(text);
Now if you needed to encode the result of the encryption (which will be binary data) as text, then you'd use base64. (Because the result of encrypting UTF-8-encoded text is not UTF-8-encoded text.)
So something like:
public static string EncryptText(string input)
{
byte[] unencryptedBytes = Encoding.UTF8.GetBytes(input);
byte[] encryptedBytes = EncryptBytes(unencryptedBytes); // Not shown here
return Convert.ToBase64String(encryptedBytes);
}
public static string DecryptText(string input)
{
byte[] encryptedBytes = Convert.FromBase64String(input);
byte[] unencryptedBytes = DecryptBytes(encryptedBytes); // Not shown here
return Encoding.UTF8.GetString(unencryptedBytes);
}

Creating a data packet in c#

I want to create a data packet and write it to socket.
This packet starts with 'C0' hex value.
In php I easily can create it with this code:
$a = "\xC0";
now I want to create it in c#. How can do this?
In C#, strings are Unicode-encoded, so you shouldn't use them for binary data. Instead use a byte array.
To create a byte array starting with C0, do something like this:
byte[] packet = new byte[] { 0xC0, /* Other values */ };
If you have an existing string that you want to send, you can use Encoding.ASCII to convert it to the bytes you need.
If you are sending bytes it's as easy as:
byte a = 0xC0;
If the packet contains text, you can start a string:
string a = "\xC0";
For more information on String Literals: http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

Encoding strings to and from base-64

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;
}

Invalid length for a Base-64 char array

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);

How can I find the starting index of a string within a UTF-8 byte array? (C#)

I have a UTF-8 byte array of data. I would like to search for a specific string in the array of bytes in C#.
byte[] dataArray = (some UTF-8 byte array of data);
string searchString = "Hello";
How do I find the first occurrence of the word "Hello" in the array dataArray and return an index location where the string begins (where the 'H' from 'Hello' would be located in dataArray)?
Before, I was erroneously using something like:
int helloIndex = Encoding.UTF8.GetString(dataArray).IndexOf("Hello");
Obviously, that code would not be guaranteed to work since I am returning the index of a String, not the index of the UTF-8 byte array. Are there any built-in C# methods or proven, efficient code I can reuse?
Thanks,
Matt
One of the nice features about UTF-8 is that if a sequence of bytes represents a character and that sequence of bytes appears anywhere in valid UTF-8 encoded data then it always represents that character.
Knowing this, you can convert the string you are searching for to a byte array and then use the Boyer-Moore string searching algorithm (or any other string searching algorithm you like) adapted slightly to work on byte arrays instead of strings.
There are a number of answers here that can help you:
byte[] array pattern search
Try the following snippet:
// Setup our little test.
string sourceText = "ʤhello";
byte[] searchBytes = Encoding.UTF8.GetBytes(sourceText);
// Convert the bytes into a string we can search in.
string searchText = Encoding.UTF8.GetString(searchBytes);
int position = searchText.IndexOf("hello");
// Get all text that is before the position we found.
string before = searchText.Substring(0, position);
// The length of the encoded bytes is the actual number of UTF8 bytes
// instead of the position.
int bytesBefore = Encoding.UTF8.GetBytes(before).Length;
// This outputs Position is 1 and before is 2.
Console.WriteLine("Position is {0} and before is {1}", position, bytesBefore);

Categories