我的項目包含2種形式,一種用於註冊用戶,另一種用於登錄。我正在使用緊湊的本地數據庫來存儲密碼。我寫了一個函數來在用戶註冊時加密密碼。然後,我寫了另一個用戶登錄時解密相同的密碼。加密/解密存儲在精簡數據庫中的密碼
第一部分,加密,工作得很好。用戶註冊,我可以看到數據庫上加密的密碼。但是,當我嘗試登錄時,密碼未被解密。這是我的功能。
Module EncryptionModule
Public Function base64Encode(ByVal sData As String) As String
Try
Dim encData_Byte As Byte() = New Byte(sData.Length - 1) {}
encData_Byte = System.Text.Encoding.UTF8.GetBytes(sData)
Dim encodedData As String = Convert.ToBase64String(encData_Byte)
Return (encodedData)
Catch ex As Exception
Throw (New Exception("Error is base64Encode" & ex.Message))
End Try
End Function
Public Function base64Decode(ByVal sData As String) As String
Dim encoder As New System.Text.UTF8Encoding()
Dim utf8Decode As System.Text.Decoder = encoder.GetDecoder()
Dim todecode_byte As Byte() = Convert.FromBase64String(sData)
Dim charCount As Integer = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length)
Dim decoded_char As Char() = New Char(charCount - 1) {}
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0)
Dim result As String = New [String](decoded_char)
Return result
End Function
End Module
這是註冊用戶的日常和加密的密碼:
Private Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
'If the username is taken or used on the
'database, then create account
If MasterTableAdapter.CheckUserName(txtUserName.Text) = Nothing Then
Dim pwd As String = base64Encode(Trim(txtConfirmPassword.Text))
MasterTableAdapter.CreateAccount(txtFName.Text, txtLName.Text, txtUserName.Text, pwd, int1)
MsgBox("An account has been created for: " & vbNewLine & _
"Employee: " & txtFName.Text & " " & txtLName.Text & vbNewLine & _
"User Name: " & txtUserName.Text & vbNewLine & _
"Access Level: " & strAccessLevel)
Me.Close()
Else
MessageBox.Show("The username is in use. Please select another username.", "Authentication Error", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End If
End Sub
這裏登錄並解密從登錄表單的密碼程序:
私人小組btnLogin_Click (發送者爲對象,例如作爲EventArgs的)把手btnLogin.Click
Dim pwd As String = base64Decode(Trim(txtPassword.Text))
If Not MasterTableAdapter.Login(txtUserName.Text, pwd) = Nothing Then
'frmWelcomePage.Show()
MsgBox("SUCCESS")
Else
'If no match, display error, clear text boxes and send focus back to the username text box.
MessageBox.Show("Username or password do not match", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtPassword.Text = Nothing
txtUserName.Text = Nothing
txtUserName.Focus()
End If
End if
End Sub
我ñ在整個加密領域,所以我不知道我在這裏做錯了什麼。
字符串轉換爲base64編碼是很難'crypting' – Steve
如果你堅持做下去你的方式,如果你編碼一個字符串,然後立即解碼它,你會得到同樣的東西嗎? – Plutonix
@Plutonix我只是試了一下,並沒有奏效。我沒有得到同樣的結果。我是新手,所以我一直在摸索。 –