0

Here 's my code and I have no idea why it produces a weird code in the console

(output is "b5?2???p?????'5???.?H???Kun???a??\??d??+\??%??A)?_???j?" without the quotes)

Private Sub TestSHA512()

    Dim key As String = "635357773463315343"
    Dim pass As String = "somepasswd"

    Dim enc As System.Text.Encoding = New System.Text.ASCIIEncoding

    Dim keyBytes() As Byte = enc.GetBytes(key)
    Dim passBytes() As Byte = enc.GetBytes(pass)

    Dim SHA As New HMACSHA512(keyBytes)

    Dim resultBytes() As Byte = SHA.ComputeHash(passBytes)

    Console.WriteLine(enc.GetString(resultBytes))
    Console.WriteLine(enc.GetString(SHA.Hash)) 'same...

End Sub
4
  • does Console.WriteLine(Convert.ToBase64String(resultBytes)) give you something more like you want? May 15, 2014 at 17:16
  • 1
    NEVER use System.Text.ASCIIEncoding this could cause hash collisions between passwords that are not the same that use characters outside of the ASCII set. Use System.Text.UTF8Encoding instead.
    – Mgetz
    May 15, 2014 at 17:21
  • 3
    Your question title says "encrypt", but SHA512 is not for encryption, it is for hashing. Which do you actually want? May 15, 2014 at 17:58
  • There are ascii characters that don't really look like characters (for example most everything < 32). It may just be a display thing. Have you looked at the actual values in the byte array and compared it to results from internet computation sites (just google sha256 computation)?
    – Jens
    May 15, 2014 at 18:05

1 Answer 1

5

First, SHA512 is a hash algorithm, not an encryption scheme, so if you're trying to encrypt then SHA512 isn't the way to do it. You'd need to look at an encryption class, such as AesManaged.

ComputeHash gives you the computed hash as a byte array. You're using ASCIIEncoding.GetString to convert that into a string, but not every byte is a printable ASCII character. That's why you're seeing the ??? characters in your console output.

If you're asking how to display the hash output as a printable string, use Convert.ToBase64String, which will convert the byte array into a string using base64 encoding. If you were expecting it in hexadecimal, you can loop through the byte array and print the Hex() value of each byte.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.