简体   繁体   中英

How to compare hash of an image using python and unity3d C#?

I have a unity3d application that request a json string of image name including its hash in my django webserver. Then my unity app will check my existing image hash if its the same as the json requested. My problem is that unity hash result is different from my python hash result value. I also tried to hash string on both and it returns the same hash value.

Python Hash:

>>> image_file = open('C:/image.png').read()
>>> hashlib.md5(image_file).hexdigest()
'658e8dc0bf8b9a09b36994abf9242099'

Unity3d Hash:

public static string ComputeHash()
{
    // Form hash
    System.Security.Cryptography.MD5 h =System.Security.Cryptography.MD5.Create();
    var myImage = File.OpenRead(PathByPlatform("image.png"));
    var data = h.ComputeHash(myImage );

    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    for (int i = 0; i < data.Length; ++i)
    {
        sb.Append(data[i].ToString("x2"));
    }
    return sb.ToString();

    //This fucntion returns 
    //fac7f19792a696d81be77aca7dd499d0
}

Did you try open('C:/image.png', "rb").read() in order to read the file in binary mode?

Reading files without the "b" will change line ending characters on Windows from CR/LF to LF which has an impact on the hash. (at least for python2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM