寻找c#等效的php的密码 – validation()

我需要将一堆用户帐户Moodle导入到用c#编写的系统中。

Moodle使用password_hash()函数创建密码哈希值。 我需要能够在c#中validation这些密码。

换句话说,我正在寻找PHP的密码validationfunction的ac#实现( http://www.php.net/manual/en/function.password-verify.php )。

我用谷歌搜索了一下但是真的找不到任何东西,所以我要求避免重新发明轮子:-)

谢谢!

得到它了!

首先通过NuGet Package安装CryptSharp。 (使用2.0“官方”包),顺便说一句,BCrypt.net不适合我。

然后:

using CryptSharp; bool matches = Crypter.CheckPassword("password goes here", "hash goes here"); 

请注意,哈希应该从以下内容开始:“$ 2y $ …”

奇迹般有效! 🙂

我知道你不想为它编写代码,.Net有一个内置的密码学库来计算哈希并加密它。 您必须通过导入Security.Cryptography来使用它。 您可以将结果与数据库中保存的结果进行比较。 这是代码。

 class Program { static int SaltValueSize = 8; static void Main(string[] args) { string pass = "Password"; string result = ComputeHash(pass, new MD5CryptoServiceProvider()); Console.WriteLine("Original: " + pass + "\nEncrypted: " + result); Console.WriteLine("Is user valid: " + IsUserValid("UserName", pass)); Console.WriteLine("With Salt, Original: " + pass + "\nEcrypted: " + System.Text.Encoding.Default.GetString(ComputePasswordHash(pass, salted))); Console.ReadLine(); } private static byte[] ComputePasswordHash(string password, int salt) { byte[] saltBytes = new byte[4]; saltBytes[0] = (byte)(salt >> 24); saltBytes[1] = (byte)(salt >> 16); saltBytes[2] = (byte)(salt >> 8); saltBytes[3] = (byte)(salt); byte[] passwordBytes = UTF8Encoding.UTF8.GetBytes(password); byte[] preHashed = new byte[saltBytes.Length + passwordBytes.Length]; System.Buffer.BlockCopy(passwordBytes, 0, preHashed, 0, passwordBytes.Length); System.Buffer.BlockCopy(saltBytes, 0, preHashed, passwordBytes.Length, saltBytes.Length); SHA1 sha1 = SHA1.Create(); return sha1.ComputeHash(preHashed); } public static string ComputeHash(string input, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes); } public static bool IsUserValid(string userName, string password) { bool isValid; string result = VerifyPassword(password); // isValid = Your database call in a form of Inverted statement which you //can check if the user with the hashed password exists or Not return isValid; } public static string VerifyPassword(string password) { return ComputeHash(password, new MD5CryptoServiceProvider()); } }