0

I'm trying to convert a byte array to a string, then at a later time convert those strings back to a byte array, but I'm getting some inconsistent results.

var salt = System.Text.Encoding.UTF8.GetString(encryptedPassword.Salt);
var key = System.Text.Encoding.UTF8.GetString(encryptedPassword.Key);
...
var saltBytes = System.Text.Encoding.UTF8.GetBytes(salt);
var keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

In this case, the original salt and key are both byte[20], but the new ones are not equal (salt being a byte[36], key a byte [41], both with totally different values).

3
  • When I use what you have above my saltBytes == Salt and my keyBytes == Key. What happens in your ... code? What are your original values? Commented Sep 17, 2015 at 23:34
  • 2
    What are the contents of encryptedPassword.Salt and encryptedPassword.Key? Arbitrary bytes? That does not work; UTF8 has rules. You cannot expect arbitrary bytes to follow the UTF8 rules. Commented Sep 17, 2015 at 23:40
  • The contents are a salt and key generated from a Rfc2898DeriveBytes. Commented Sep 17, 2015 at 23:42

1 Answer 1

2

Basically what @DourHighArch said. You can go string->binary->string, but you can't expect to be able to go binary->string->binary using text encoding.

For what you are doing, you probably want to use something like base64 encoding. So you could write it like this:

var salt = Convert.ToBase64String(encryptedPassword.Salt);
var key = Convert.ToBase64String(encryptedPassword.Key);
...
var saltBytes = Convert.FromBase64String(salt);
var keyBytes = Convert.FromBase64String(key);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explaination! Using base64 encoding is working and what I was intending to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.