Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Cryptography.SHA512 gives unexpected output

Discussion in 'Scripting' started by Plato, May 14, 2014.

  1. Plato

    Plato

    Joined:
    Jun 24, 2013
    Posts:
    15
    Hi,
    I have to convert passwords to SHA512 encrypted before sending them to server.
    I got the code to convert the string to SHA512 from this linkhttp://forum.unity3d.com/threads/212398-Turn-a-string-into-SHA512

    Code (csharp):
    1. string s = "Hello World";
    2. byte[] bytes = System.Text.Encoding.ASCII.GetBytes( s );
    3. System.Security.Cryptography.SHA512 sha = System.Security.Cryptography.SHA512.Create();
    4. byte[] hash = sha.ComputeHash( bytes );
    5. string result = System.Text.Encoding.ASCII.GetString( hash );
    6. Debug.Log( result );
    if i run this code i'm gettting result like this

    and to cross check the result i checked the SHA512 value of Hello World in this link http://www.miniwebtool.com/sha512-hash-generator/. The result is totally different from what i'm getting in unity.

    Am i doing something wrong while encrypting?
    Or is there any other way i can encrypt without using default unity class?
     
  2. Loius

    Loius

    Joined:
    Aug 16, 2012
    Posts:
    546
    The first one looks like a string of characters, the second one looks like a hex code. Comma is 2C so I'm not sure they're equivalent, but they could both be right (since yours is going through several functions). Can you decrypt your own string to an expected value?
     
  3. Plato

    Plato

    Joined:
    Jun 24, 2013
    Posts:
    15
    @Loius

    the 1st one is the output i'm getting and the second one is the output i'm supposed to get.
    Anyway i found another solution for this problem. Not entirely sure why this is working but this code gave the correct output.

    Code (csharp):
    1.  
    2. Encoding ue = Encoding.UTF8;
    3. byte[] hashalue;
    4. byte[] msg = ue.GetBytes(pString);
    5.  
    6. SHA512Managed hashString = new SHA512Managed();
    7. string hex = "";
    8. hashalue = hashString.ComputeHash(msg);
    9. //hex = ue.GetString( hashalue );
    10. foreach(byte x in hashalue) {
    11.     hex += string.Format("{0:x2}", x);
    12. }
    13. return hex;
    14.