Reputation: 124
var test = "sdfsdfsdfasfwerqwer";
var q = UTF8Encoding.UTF8.GetBytes(test);
var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(q);
var z = UTF8Encoding.UTF8.GetString(hash);
var t = UTF8Encoding.UTF8.GetBytes(z);
In the above example, hash and t have different values. Why is this?
Upvotes: 0
Views: 1039
Reputation: 11903
hash
is not an UTF-8 encoded byte array, just some random bytes. Note: not all byte arrays are valid as UTF-8, UTF-8 has its own rules. Therefore, it cannot necessarily be decoded into a string. (Specifically, invalid bytes are usually decoded into a question mark in .NET.)
You can try a regular 8-bit encoding which supports all possible byte arrays, like ISO-8859-1. Of course you will still get garbage when you try to read that as a string, but it should work back and forth.
If you are trying to transfer a random byte array as a string, I suggest you use BASE-64 encoding, which converts byte arrays to an ASCII string, which should be safe in all circumstances.
Upvotes: 4