在 VB.NET 中使用 MD5 进行散列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23513831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:30:29  来源:igfitidea点击:

Hash with MD5 in VB.NET

vb.nethashmd5

提问by Koinzell

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.

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

Here is my login class

这是我的登录类

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

回答by ??ssa P?ngj?rdenlarp

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.

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

See this answerfor hashing using SHA.

请参阅此答案以使用 SHA 进行散列。



For passwords, you'd save the hashof 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

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

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

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

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):

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

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

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 应该使用加密随机数生成器创建,如SHA 版本中所示。将 salt 转换为文本(十六进制或 Base64),然后与 PW 结合以获得 PW 哈希。



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):

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

 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

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

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

  thisHash = CryptoTools.GetHash(strToHash) 

Note: Hashing is case sensitive, so foobarwill result in a different hash than FooBaror FOOBAR. To create a case insensitivesystem, convert the original string (such as a password) to lowercase before you compute the MD5 hash value to be saved, anddo the same for the value they later enter:

注意:散列是区分大小写的,因此foobar会导致与FooBar或不同的散列FOOBAR。要创建一个大小写不敏感的系统,转换成原始的字符串(如密码),以小写用户使用电脑时要保存的MD5哈希值之前,为他们以后输入值做同样的:

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

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

回答by Bender

  1. MD5 Convertion
  1. MD5 转换
Dim [source] As String = password_text_box.text 
Using md5Hash As MD5 = MD5.Create()
Dim hash As String = GetMd5Hash(md5Hash, source)
Dim [source] As String = password_text_box.text 
Using md5Hash As MD5 = MD5.Create()
Dim hash As String = GetMd5Hash(md5Hash, source)

2, Insert Name and hash into database

2、将Name和hash插入到数据库中

3, Validation

3、验证

During login take MD5 of password again run sql query

在登录时再次获取密码的 MD5 运行 sql 查询

Select name,password from table where Login ='" & username & "' and Password ='" & md5(user input pass) & "'

从表中选择名称、密码,其中 Login ='" & username & "' and Password='" & md5(user input pass) & "'

if dreader returns value , then valid login else invalid login

如果 dreader 返回值,则登录有效,否则登录无效

回答by mirko cro 1234

   Private Function GetHash(strToHash As String) As String

    Dim md5Obj As New System.Security.Cryptography.MD5CryptoServiceProvider
    Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)

    bytesToHash = md5Obj.ComputeHash(bytesToHash)
    Dim strResult As New StringBuilder

    For Each b As Byte In bytesToHash
        strResult.Append(b.ToString("x2"))
    Next

    Return strResult.ToString

End Function

回答by Indra Noprida IN

This would be my solution:

这将是我的解决方案:

Public Sub _Enkripsi()

    Dim _DES As New TripleDESCryptoServiceProvider()
    Dim _HashMD5 As New MD5CryptoServiceProvider()

    _DES.Key = _HashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(PasswordTextBox.Text))
    _DES.Mode = CipherMode.ECB
    Dim _DESEncrypt As ICryptoTransform = _DES.CreateEncryptor()
    Dim _Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(PasswordTextBox.Text)
    _Password = Convert.ToBase64String(_DESEncrypt.TransformFinalBlock(_Buffer, 0, _Buffer.Length))

End Sub