How can I reproduce a SHA512 hash in C# that fits the PHP SHA512?

我们两清 提交于 2019-11-30 20:35:29

Try this

using System.Security.Cryptography

public static string HashPassword(string unhashedPassword)
{
    return BitConverter.ToString(new SHA512CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(unhashedPassword))).Replace("-", String.Empty).ToUpper();
}

BitConverter works just fine ...

var testVal = "asdasd";
var enc = new ASCIIEncoding();
var bytes = enc.GetBytes( testVal );

var sha = new SHA512Managed();
var result = sha.ComputeHash( bytes );

var resStr = BitConverter.ToString( result );
var nodash = resStr.Replace( "-", "" );

nodash.Dump();

(Fixed for 512-bit hash, sorry :)

ww1981

I just spent several hours trying to get a .NET hash function to match PHP's Crypt function. Not fun.

There are multiple challenges here, since the PHP implementation of Crypt returns a base64 encoded string, and doesn't do multiple hashing iterations (e.g. 5000 is default for Crypt.) I was not able to get similar outputs from .NET using several libraries, until I found CryptSharp. It accepts a salt similar to PHP's (or the original C) function (e.g. "$6$round=5000$mysalt"). Note that there is no trailing $, and that if you don't provide a salt it will autogenerate a random one.

You can find CryptSharp here: http://www.zer7.com/software.php?page=cryptsharp

Good background reading: - http://www.akkadia.org/drepper/SHA-crypt.txt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!