如何sha1哈希一个c#登录应用程序

时间:2016-05-09 08:11:25

标签: c# sql sql-server

我想将密码设为哈希密码,例如sha1我尝试将其设为PassLogin = sha1(@PassLogin)但是它无法正常工作

这是我的代码

using (SqlCommand cmd = new SqlCommand("SELECT * FROM LoginReport where UserLogin = @UserLogin and PassLogin = @PassLogin", conn))
{
    conn.Open();

    cmd.Parameters.AddWithValue("@UserLogin", txtUser.Text);
    cmd.Parameters.AddWithValue("@PassLogin", txtPass.Text);
    SqlDataReader Dr = cmd.ExecuteReader();
    if (Dr.HasRows == true)
    {
        MessageBox.Show("Successfully Login");
        Form1 FormReports = new Form1();                         
        FormReports.ShowDialog();
        Application.Exit();

    }
    else
    {
        MessageBox.Show("Check username and password again!!");
    }
}

1 个答案:

答案 0 :(得分:0)

在将其指定为参数之前,您似乎并未真正对该值进行哈希处理。

您可能首先想要尝试哈希输入字符串,请参阅包含的代码(未测试!)以获取示例如何执行此操作:

public static string GenerateSaltedSHA1(string plainTextString)
{
      HashAlgorithm algorithm = new SHA1Managed();
      var saltBytes = GenerateSalt(4);
      var plainTextBytes = Encoding.ASCII.GetBytes(plainTextString);

      var plainTextWithSaltBytes = AppendByteArray(plainTextBytes, saltBytes);
      var saltedSHA1Bytes = algorithm.ComputeHash(plainTextWithSaltBytes);
      var saltedSHA1WithAppendedSaltBytes = AppendByteArrays(saltedSHA1Bytes, saltBytes);

      return "{SSHA}" + Convert.ToBase64String(saltedSHA1WithAppendedSaltBytes);
} 

private static byte[] GenerateSalt(int saltSize)
{
     var rng = new RNGCryptoServiceProvider();
     var buff = new byte[saltSize];
     rng.GetBytes(buff);
     return buff; 
}

private static byte[] AppendByteArray(byte[] byteArray1, byte[] byteArray2)
{
    var byteArrayResult =
            new byte[byteArray1.Length + byteArray2.Length];

    for (var i = 0; i < byteArray1.Length; i++)
         byteArrayResult[i] = byteArray1[i];
    for (var i = 0; i < byteArray2.Length; i++)
         byteArrayResult[byteArray1.Length + i] = byteArray2[i];

    return byteArrayResult;
}

我想建议您使用比SHA1更强的哈希算法,因为使用当前技术可以轻松创建巨大的彩虹表,以便轻松找到哈希的原始字符串。请为你的哈希加盐!