Password encryption deycrption UTF8 Encoding String conversion doesn't work

I wanna save a password encrypted in a local database (on windows phone). For that I first have to encrypt the password with this.

byte[] passwordInByte = UTF8Encoding.UTF8.GetBytes(clearPW);
byte[] protectedPasswordByte = ProtectedData.Protect(passwordInByte, null);
return UTF8Encoding.UTF8.GetString(protectedPasswordByte, 0, protectedPasswordByte.Length);

When I use this I get the encyrpted password like this:

"\0賐�ᔁᇑ窌쀀쉏\0쐮�毸䉯놜侫䅛\0\0\0\0昐\0Ā\0 \0⎛폳띪ꌾၜჸ㸴뀲േꞪ賂ﯛ䎳웠姒\0\0耎\0Ȁ\0 \0tƽ팃ல�쿄갗ꪄ᫓\0꒱௴贒⊡噷�ʥ魚@\0챞Ċ뽨뒸縉菒Æ�≁ᦹ諻⋤떵孵ר䒹춳✴頻ľ�뚿㠔꾹놼ɝ⍔" And the protected passwordPasswordByte is has a length of 230 bytes.

My decryption function looks like this:

byte[] encryptedBytes = UTF8Encoding.UTF8.GetBytes(encrytpedPW);
byte[] passwordByte = ProtectedData.Unprotect(encryptedBytes, null);
return UTF8Encoding.UTF8.GetString(passwordByte, 0, passwordByte.Length);

Now the enycrptedBytes array is 290 bytes length and the password cannot be even decrypted because the Unprotect function throws the error "Invalid data"

But everything works fine in case I use the Convert.BaseString64 functions like this:

encryption:

byte[] passwordInByte = UTF8Encoding.UTF8.GetBytes(clearPW);
byte[] protectedPasswordByte = ProtectedData.Protect(passwordInByte, null);
return Convert.ToBase64String(protectedPasswordByte, 0, protectedPasswordByte.Length);

decryption:

byte[] encryptedBytes = Convert.FromBase64String(encrytpedPW);
byte[] passwordByte = ProtectedData.Unprotect(encryptedBytes, null);
return UTF8Encoding.UTF8.GetString(passwordByte, 0, passwordByte.Length);

Does anybody of you has an idea what is so wrong about the UTF8 encoding? Because the first way is the recommended was by MSDN.

Jon Skeet
people
quotationmark

Just don't do this:

return UTF8Encoding.UTF8.GetString(protectedPasswordByte, 0, protectedPasswordByte.Length);

Firstly, I'd strongly advise using Encoding.UTF8 instead of UTF8Encoding.UTF8, for clarity. That won't fix the problem, but it's a good habit to get into - the UTF8 property is declared on Encoding, not UTF8Encoding, so it's clearer to acknowledge that.

The main problem is that you've just not got text data. You shouldn't use Encoding.GetString when the binary data you've got isn't regular encoded text data. You've got arbitrary binary data which doesn't represent text (until it's decrypted).

Base64 is precisely designed to represent any binary data in ASCII text - so you don't end up losing any data due to binary data which simply doesn't have any "straight" text representation in whatever encoding you decide to use. You should use Base64 - or hex, or something similar - any time you want to encode arbitrary binary data as text.

people

See more on this question at Stackoverflow