I am working on encrypting and decrypting user passwords. I am working on this usingmvc3 vb.net and sql server 2008 for the database. I am able to encrypt the password but I couldnt decrypt it and everytime i try to decrypt it, it would give a a 'bad data' error. Pls help! Need to fix this asap.
Here's the codes:
Code:Imports System.Security.Cryptography Imports System.IO Imports System.Text Public NotInheritable Class PasswordEncryption Private TripleDes As New TripleDESCryptoServiceProvider Private Function TruncateHash( ByVal key As String, ByVal length As Integer) As Byte() Dim sha1 As New SHA1CryptoServiceProvider Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ReDim Preserve hash(length - 1) Return hash End Function Sub New(ByVal key As String) TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8) TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8) End Sub Public Function EncryptData( ByVal plaintext As String) As String Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext) Dim ms As New System.IO.MemoryStream Dim encStream As New CryptoStream(ms, TripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write) encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() Return Convert.ToBase64String(ms.ToArray) End Function Public Function DecryptData( ByVal encryptedtext As String) As String Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) Dim ms As New System.IO.MemoryStream Dim decStream As New CryptoStream(ms, TripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write) Try decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() Catch ex As Exception End Try Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Function End Class
and here's my code for the controller:
Code:Function ViewUsers(ByVal users As Users) As ViewResult Dim pwordList = New List(Of String)() Dim pwordQuery = From pword In db.UsersDB Select pword.Password pwordList.AddRange(pwordQuery) For Each pass As String In pwordList PassEncrypt = New PasswordEncryption(pass) PassEncrypt.DecryptData(pass) Next Return View(db.UsersDB) End Function




Reply With Quote