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

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

问题描述

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



这是我的登录类

  Imports System.Data 

Imports System.Data.SqlClient

Imports System.Data.SqlServerCe

公共类登录

继承System.Web。 UI.Page


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

如果Bibliothek.EntryExists(LNAME.Text, Username)= False然后
LNAMELBL.Text =名字或密码Falsch。
退出子
结束如果

如果Bibliothek.EntryExists(LPW.Text,Passwort)= False那么
LNAMELBL.Text =名称或Passwort Falsch。
Exit Sub
End If
Dim UserN As String = LNAME.Text
Session(Admin)= Bibliothek.GetValueBool(UserN,IsAdmin)
Session (USERNA)= Bibliothek.GetValueBool(UserN,用户名)

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

End Class


解决方案

重要的是要注意MD5不再被认为是一件好事散列您希望保护的数据的方法。请参阅wikipedia以了解有关这些漏洞的讨论。



查看此答案用于使用SHA进行散列。






对于密码,您可以保存 用户的PW到数据库。因为它是单向的(你不能轻易从哈希中获得原始值),这可以防止像看门人或客户服务代表这样的人能够看到数据库中的实际密码。

  Imports System.Security.Cryptography 
Imports System.Text

Shared Function GetHash( theInput As String)As String

使用散列函数作为MD5 = MD5.Create()'创建散列对象

'转换为字节数组并获取散列值
Dim dbytes As Byte()=
hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput))

'sb从字节创建字符串
Dim sBuilder As New StringBuilder()

'将字节数据转换为十六进制字符串
For n As Integer = 0 To dbytes.Length - 1
sBuilder.Append(dbytes(n).ToString(X2))
Next n

返回sBuilder.ToString()
结束使用

End Function

根据你想要保存的方式,而不是使用 StringBuilder 创建一个十六进制字符串,你可以使用 Convert.ToBase64String()

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

散列应该使用 salt 来完成。这是添加到散列的数据,使结果更难以预测(有普通PW的散列结果的字典,例如password; salt会改变结果):

<$共享函数GetHash(theInput As String,theSalt As String)As String
...
hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput& theSalt) )

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






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

<$ p $ b $ 共享函数CheckHash(hashedStr As String,newInput As String)As Boolean
'获取用户输入的散列值:
Dim newHash As String = GetHash(newInput& dbSalt)

'返回比较
返回String.Compare(newHash,hashedStr,InvariantCultureIgnoreCase)
End Function

正如所写, GetHash 函数旨在用于像CryptoTools类之类的东西。因为它是共享/静态的,所以类不需要实例:

  thisHash = CryptoTools.GetHash(strToHash)

注意:散列区分大小写,所以 foobar 会导致与 FooBar FOOBAR 不同的散列。要创建不区分大小写的系统,请在计算要保存的MD5哈希值之前将原始字符串(例如密码)转换为小写,对他们稍后输入的值:

 'ToLowerInvariant允许外部字符集
Dim str As String = PWTextBox.Text.ToLowerInvariant

如果CheckHash(dbHashedValue,str)then
'okie dokie
else
'failed
End If


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

解决方案

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.

See this answer for hashing using SHA.


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

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==

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 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.


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

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) 

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天全站免登陆