ISSUE :
 
Profile photo
Submitted by G-Stone
on May 21st, 2011 at 09:49:14 EST

Problem using Encoding.UTF8.GetString() and Encoding.UTF8.GetBytes()

I get binary data from my encryption class. I tried to convert my binary data to string using Encoding.UTF8.GetString() so that I can store in string field in database. Later I read my string from database, convert string to binary byte using Encoding.UTF8.GetBytes() and try to decrypt the binary byte. But this is not working.

Now my problem is when I convert my binary bytes to string using Encoding.UTF8.GetString() and convert back string to bytes using Encoding.UTF8.GetBytes(), the results are not same. I am not sure if I am doing anything wrong here. I am trying to convert my binary bytes to string so that I can store as string?


Profile photo
Replied by G-Stone
on May 21st, 2011 at 09:49:35 EST
I am using C# .NET for this.

Profile photo
Replied by RaKumar
on May 21st, 2011 at 16:17:31 EST
You can not just use Encoding.UTF8.GetString() and Encoding.UTF8.GetBytes() to convert binary bytes to string and back forth. Encoding.UTF8.GetString() will give you string representation from bytes only if the bytes contain string data.

If you want to convert your binary bytes to string for storage, convert to Base64 encoding and store it. Later decode from base64 to binary bytes again.

To convert to base64 string from bytes in C#:
Convert.ToBase64String();

To convert to bytes from base64 string:
Convert.FromBase64String();
Accepted Answer
Accepted
 Answer

Profile photo
Replied by G-Stone
on May 21st, 2011 at 16:37:08 EST
Now, I know what I am doing wrong. Converting to base64 string solves my issue. thanks.

Profile photo
Replied by Sagnik Majumder
on January 3rd, 2013 at 02:49:17 EST
As correctly pointed out by RaKumar, if you want to convert your binary bytes to string for storage, convert to Base64 encoding and store it. Later decode from base64 to binary bytes again.

You can follow this code snippet below:-
  
string password = "abc@123";
string decryptedpassword = string.Empty;
string encryptedpassword = Convert.ToBase64String(Encoding.UTF8.GetBytes(password));
Byte[] encBytes = Convert.FromBase64String(encryptedpassword);
decryptedpassword = Encoding.UTF8.GetString(encBytes, 0, encBytes.Length);

/*** You will see password = decryptedpassword. ***/