寻找c#等效的php' s密码验证()

时间:2014-03-24 16:52:43

标签: c# php passwords cryptography

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

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

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

我谷歌搜索了一下,但实际上找不到任何东西,所以我希望避免重新发明轮子: - )

谢谢!

2 个答案:

答案 0 :(得分:11)

知道了!

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

然后:

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

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

像魅力一样! : - )

答案 1 :(得分:-4)

我知道你不想为它编写代码,.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());
    }


}