Converting from byte to string and back to byte ends in different results?

M

mfunkmann

Hi there,

I have a really strange conversion-problem here:

--
string _content = new string("some data");

...

System.Text.Encoding _Convert= new System.Text.ASCIIEncoding();
byte[] _encrypted =
_Encrypt.TransformFinalBlock(_Convert.GetBytes(_content), 0,
_Convert.GetByteCount(_content));
_content = _Convert.GetString(_encrypted);
byte[] _t = _Convert.GetBytes(_content);
--

_t differs from _enrypted

I another testprogram I have following code:

--
System.Text.Encoding _Convert = new System.Text.ASCIIEncoding();
byte[] test = { 44, 59, 56, 78, 67, 89, 67, 86 };
text = _Convert.GetString(test);
byte[] _new = _Convert.GetBytes(text);
--

and here _new is equal to test!



Even pasting the code from the testprogram and changing the parameters
accordingly did not work.


I really don't know what to do anymore..

Any ideas?
 
J

Jon Skeet [C# MVP]

I have a really strange conversion-problem here:

It's not really strange at all.

Encryption gives arbitrary binary data. Converting that into ASCII is a
lossy operation, as ASCII only defines values under 128. You shouldn't
treat arbitrary binary data as if it were encoded text. Use something
like Base64 instead (see Convert.ToBase64String and
Convert.FromBase64String).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top