在 VB.NET 中使用 MD5 进行散列 [英] Hash with MD5 in VB.NET

查看:21
本文介绍了在 VB.NET 中使用 MD5 进行散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我这里有点问题,我有一个数据库,一个登录和一个注册,都在不同的类中,现在我需要在数据库中散列密码并在登录时再次读取它,但是我不知道如何处理这个,我已经搜索了很多但找不到任何有用的东西.

So, I got a bit of a problem here, I got a database, a login and a registration, all in different classes, now I need to hash the password in the database and read it out again when logging in, but I don't know how to handle this, I already searched a lot but couldn't find anything useful.

这是我的登录类

Imports System.Data

Imports System.Data.SqlClient

Imports System.Data.SqlServerCe

Public Class Login

    Inherits System.Web.UI.Page


    Private Sub LSend_Click(sender As Object, e As System.EventArgs) Handles LSend.Click

        If Bibliothek.EntryExists(LNAME.Text, "Username") = False Then
            LNAMELBL.Text = "Name oder Passwort Falsch."
            Exit Sub
        End If

        If Bibliothek.EntryExists(LPW.Text, "Passwort") = False Then
            LNAMELBL.Text = "Name oder Passwort Falsch."
            Exit Sub
        End If
        Dim UserN As String = LNAME.Text
        Session("Admin") = Bibliothek.GetValueBool(UserN, "IsAdmin")
        Session("USERNA") = Bibliothek.GetValueBool(UserN, "Username")

        Response.Redirect("/TSL/Home.aspx")
    End Sub
    Private Sub REG_Click(sender As Object, e As System.EventArgs) Handles REG.Click
        Response.Redirect("/TSL/Registrierung.aspx")
    End Sub

End Class

推荐答案

请务必注意,MD5 不再被视为散列您希望保护的数据的好方法.有关漏洞的讨论,请参阅维基百科.

It is important to note that MD5 is no longer considered a good way to hash data you wish to protect. See wikipedia for a discussion of the vulnerabilities.

有关使用 SHA 进行散列的信息,请参阅此答案.

对于密码,您需要将用户密码的 hash 保存到数据库中.因为它是单向的(你不能轻易地从散列中取回原始值),这可以防止像管理员或客户服务代表这样的人能够看到数据库中的实际密码.

For passwords, you'd save the hash of the user's PW to the DB. Because it is one-way (you cannot easily get the original value back from the hash), this prevents someone like a janitor or customer service rep from being able to see the actual passwords in the database.

Imports System.Security.Cryptography
Imports System.Text

Shared Function GetHash(theInput As String) As String

    Using hasher As MD5 = MD5.Create()    ' create hash object

        ' Convert to byte array and get hash
        Dim dbytes As Byte() = 
             hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput))

        ' sb to create string from bytes
        Dim sBuilder As New StringBuilder()

        ' convert byte data to hex string
        For n As Integer = 0 To dbytes.Length - 1
            sBuilder.Append(dbytes(n).ToString("X2"))
        Next n

        Return sBuilder.ToString()
    End Using

End Function

根据您想要如何保存它,而不是使用 StringBuilder 创建十六进制字符串,您可以使用 Convert.ToBase64String():

Depending on how you want to save it, rather than a using StringBuilder to create a hex string, you can use Convert.ToBase64String():

Return Convert.ToBase64String(dbytes)
' MyWeakPassword hashed:
'     to hex: DB28F1BE20A407398171295DD0D191E2
'  to Base64: 2yjxviCkBzmBcSld0NGR4g==

散列应该用 salt 完成.这是添加到哈希中的数据,以使结果更难预测(有常用 PW 哈希结果的字典,例如密码";salt 更改结果):

Hashing should be done with salt. This is data added to the hash to make the result less predictable (there are dictionaries of the hashed results of common PW such as "password"; salt changes the outcome):

Shared Function GetHash(theInput As String, theSalt As String) As String
...
      hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput & theSalt))

Salt 应使用加密随机数生成器创建,如SHA 版本所示.将salt 转换为文本(十六进制或Base64),然后与PW 结合得到PW 哈希.

Salt should be created using the Cryptographic random number generator as shown in the SHA Version. Convert the salt to text (hex or Base64) then combine with the PW to get the PW hash.

要检查/比较用户的条目,只需对输入进行散列并将其与存储在数据库中的散列进行比较,使用相同的 Salt(这意味着需要保存 Salt):

To check/compare a user's entry, simply hash the input and compare it to the hash stored in the database, using the same Salt (which means the Salt needs to be saved):

 Shared Function CheckHash(hashedStr As String, newInput As String) As Boolean
    ' get the hash value of user input: 
    Dim newHash  As String = GetHash(newInput & dbSalt) 

    ' return comparison
    Return String.Compare(newHash, hashedStr, InvariantCultureIgnoreCase)
 End Function

正如所写的那样,GetHash 函数旨在从 CryptoTools 类之类的东西中使用.由于它是共享/静态类,因此不需要实例化:

As written, the GetHash function is intended to be used from something like a CryptoTools Class. Since it is Shared/Static the class need not be instanced:

  thisHash = CryptoTools.GetHash(strToHash) 

注意:散列区分大小写,因此 foobar 将产生与 FooBarFOOBAR 不同的散列.要创建不区分大小写的系统,请在计算要保存的 MD5 哈希值之前将原始字符串(例如密码)转换为小写,对他们后来输入的值:

Note: Hashing is case sensitive, so foobar will result in a different hash than FooBar or FOOBAR. To create a case insensitive system, convert the original string (such as a password) to lowercase before you compute the MD5 hash value to be saved, and do the same for the value they later enter:

' ToLowerInvariant allows for foreign char sets
Dim str As String = PWTextBox.Text.ToLowerInvariant

If CheckHash(dbHashedValue, str) Then
    ' okie dokie
Else
    ' failed
End If

这篇关于在 VB.NET 中使用 MD5 进行散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆