Imports System.Data.SqlClient
Imports System.Web.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Imports System.Web.Security.FormsAuthentication

 

 ''CreateSalt 產生經過 RNGCryptoServiceProvider 所加密的亂數
    ''這是被用來傳遞給CreateHash()做串連使用者前端畫面所輸入的密碼之方法
    Public Function CreateSalt() As String
        Dim rng As New RNGCryptoServiceProvider '實作密碼編譯亂數產生器 (RNG)。
        Dim size As Integer
        size = CInt(Int((20 * Rnd()) + 1))
        Dim buff() As Byte = New Byte(size) {}
        rng.GetBytes(buff)
        Return Convert.ToBase64String(buff)
    End Function

'=============================================

    ''CreateHash 產生雜湊運算後的字串
    ''salt 為CreateSalt() 所產生的加密字串
    ''pwd 為前端使用者在畫面所輸入的密碼
    Public Function CreateHash(ByVal pwd As String, ByVal salt As String) As String
        Dim saltPwd As String = String.Concat(pwd, salt)
        Dim data() As Byte = Encoding.UTF8.GetBytes(saltPwd)
        Dim result() As Byte
        Dim shaM As New SHA1Managed
        result = shaM.ComputeHash(data)
        Dim hashPwd As String = Convert.ToBase64String(result)

        Return hashPwd
    End Function

'=============================================

    ''pwd 未加密過的密碼,也就是前端使用者所輸入的密碼
    ''hashedPwd 已儲存在資料庫中且加密過的密碼
    ''salt 已儲存在資料庫中且經過 RNGCryptoServiceProvider 所產生的加密亂數

    Public Function CheckAuthentication(ByVal pwd As String, ByVal salt As String, ByVal hashedPwd As String) As Boolean
        Dim hashPwdcmp As String = CreateHash(pwd, salt)
        Dim cp As Boolean
        If hashedPwd.Equals(hashPwdcmp) Then
            cp = True
        Else
            cp = False
        End If
        Return cp
    End Function

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 alen1985 的頭像
    alen1985

    1與0的世界

    alen1985 發表在 痞客邦 留言(0) 人氣()