Decrypt md5 in vb.net - vb.net

i try to make function for lost password in my website using vb.net the code below is fore encrypt
Function getMD5Hash(ByVal 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 String = ""
For Each b As Byte In bytesToHash
strResult += b.ToString("x2")
Next
Return strResult
End Function

MD5 is a hashing algorithm, not a bidirectional encryption system.
For lost password, you should send a password reset token instead of sending the end user the password.

Related

Problems with encryption and decryption TripleDES in vb.net

I'm practicing encryption and decryption with a text file by using TipleDES. I enter a word in a text box, which is in my application, and then click my button that will store the password in the text file. I check the text file to see if it encrypts it which it does and then I try to decrypt the text. It encrypts it again and doesn't decrypt it. I'm not sure what I'm doing wrong.
Public Function EncryptTripleDES(strInput As String, btKey As String) As String
Dim desTDES As New TripleDESCryptoServiceProvider()
Dim hashMD5TDES As New MD5CryptoServiceProvider()
Dim btHash As Byte()
Dim btBuff As Byte()
btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
desTDES.Key = btHash
desTDES.Mode = CipherMode.ECB
btBuff = Encoding.UTF8.GetBytes(strInput)
Dim strResult As String = Convert.ToBase64String _
(desTDES.CreateEncryptor().TransformFinalBlock(btBuff, 0,
btBuff.Length))
Return strResult
End Function
Public Function DecryptTripleDES(strInput As String, btKey As String) As String
Dim desTDES As New TripleDESCryptoServiceProvider()
Dim hashMD5TDES As New MD5CryptoServiceProvider()
Dim btHash As Byte()
Dim btBuff As Byte()
btHash = hashMD5TDES.ComputeHash(Encoding.UTF8.GetBytes(btKey))
desTDES.Key = btHash
desTDES.Mode = CipherMode.ECB
btBuff = Convert.FromBase64String(strInput)
Dim strResult As String = Encoding.UTF8.GetString _
(desTDES.CreateDecryptor().TransformFinalBlock(btBuff, 0,
btBuff.Length))
Return strResult
End Function
These are my functions to encrypt and decrypt.
strEncode = EncryptTripleDES(EmailPasswordTextBox.Text, "HTG")
strDecode = DecryptTripleDES(strEncode, "HTG")
Console.WriteLine("Encrypted: {0}", strEncode)
Console.WriteLine("Decrypted: {0}", strDecode)
If I change EmailPasswordTextBox.Text to "This is a Test". It works perfectly. What am I doing wrong?

How to decrypt a MD5 hash

I have used the following function to encrypt my password:
HashPasswordForStoringInConfigFile(Password, "MD5")
Now I want to decrypt the password again.
Note I'm showing the encrypted password in a grid-view and I want to decrypt it when the particular row goes in edit mode.
The simple answer is "you can't"
The idea of hashing is to generate a "safe" code from the real password, where that code can be stored in clear text; in a database (or text file) somewhere where other users might be seeing it somehow.
When someone tries to login, your system would compute another hash from the new login and then compare with the existing hash from your existing database, if the hash matches, then you know it's the correct password and then you can allow them to login, otherwise, it's not the same password / login-failed.
The reason why you cannot reverse the hash is because a hash is computed by doing the following steps:
1) Taking the password into some algorithm to:
2) Generate a very large string, then:
3) Chop that string and:
4) Take a part of it as your "hash"
So you see, even if you are superman in decoding and can figure the algorithm out, and know the hash code, and managed to reverse it back into the original form, then you would still have parts of the password missing, hence unsuccessful.
This is why Hashes are secure.
I hope this explains it.
you can make encrypt and decrypt function like this to encrypt and decrypt your text , and further u can use as per your need to display the decrypt text
here is the function
Public Function Encrypt(ByVal plainText As String) As String
Dim passPhrase As String = "yourPassPhrase"
Dim saltValue As String = "mySaltValue"
Dim hashAlgorithm As String = "MD5"
Dim passwordIterations As Integer = 2
Dim initVector As String = "#1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
Dim memoryStream As New MemoryStream()
Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
cryptoStream.FlushFinalBlock()
Dim cipherTextBytes As Byte() = memoryStream.ToArray()
memoryStream.Close()
cryptoStream.Close()
Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
Return cipherText
End Function
and for decrypt use this
Public Function Decrypt(ByVal cipherText As String) As String
Dim passPhrase As String = "yourPassPhrase"
Dim saltValue As String = "mySaltValue"
Dim hashAlgorithm As String = "MD5"
Dim passwordIterations As Integer = 2
Dim initVector As String = "#1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256
' Convert strings defining encryption key characteristics into byte
' arrays. Let us assume that strings only contain ASCII codes.
' If strings include Unicode characters, use Unicode, UTF7, or UTF8
' encoding.
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
' Convert our ciphertext into a byte array.
Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
' First, we must create a password, from which the key will be
' derived. This password will be generated from the specified
' passphrase and salt value. The password will be created using
' the specified hash algorithm. Password creation can be done in
' several iterations.
Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
' Use the password to generate pseudo-random bytes for the encryption
' key. Specify the size of the key in bytes (instead of bits).
Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
' Create uninitialized Rijndael encryption object.
Dim symmetricKey As New RijndaelManaged()
' It is reasonable to set encryption mode to Cipher Block Chaining
' (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC
' Generate decryptor from the existing key bytes and initialization
' vector. Key size will be defined based on the number of the key
' bytes.
Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
' Define memory stream which will be used to hold encrypted data.
Dim memoryStream As New MemoryStream(cipherTextBytes)
' Define cryptographic stream (always use Read mode for encryption).
Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
' Since at this point we don't know what the size of decrypted data
' will be, allocate the buffer long enough to hold ciphertext;
' plaintext is never longer than ciphertext.
Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
' Start decrypting.
Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
' Close both streams.
memoryStream.Close()
cryptoStream.Close()
' Convert decrypted data into a string.
' Let us assume that the original plaintext string was UTF8-encoded.
Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
' Return decrypted string.
Return plainText
End Function
and call the function you will get the result.

How much salt security is too much salt security

When does salting passwords become too secure? I have a couple of functions that Encrypt and Decrypt as users passwords, but I am concerned if it might be overkill.
First I have my encryption method which takes the encrypted password and the salt and puts it all in one string (up to 256 Characters) in my database. In addition to that it actually only encrypts the password with a 32 Character string of my original 128 Character Salt String, which the function chooses at random.
Public Function EncryptPassword(Password As String) As String
Dim EPassword As String = String.Empty
' Generate Random 128 Base64 Salt String
Dim Salt As String = Var.Simple3Des.GenerateSalt
' Divide into Substrings, and combine into splitable string
Dim SmallSalts As String = Salt.Substring(0, 32) + "." + Salt.Substring(32, 32) + "." + Salt.Substring(64, 32) + "." + Salt.Substring(96, 32)
' Create the Salt Array
Dim SaltArray = Split(SmallSalts, ".")
' Randomly Choose part of the array to actually use as salt
Dim rnd As New Random
Dim TrueSalt As String = SaltArray(rnd.Next(0, SaltArray.Length))
' Encrypt The Password
Dim Security As New Var.Simple3Des(TrueSalt)
EPassword = Security.EncryptData(Password)
' Divide up the salt and password and place into same string
Dim PasswordString As String = Salt.Substring(0, 16) + EPassword.Substring(0, 6) + Salt.Substring(16, 112) + EPassword.Substring(6, EPassword.Length - 6)
Return PasswordString
End Function
I then use the same formula to Decry-pt the password, by trying all possible sub-string combinations until it finds the right one.
Public Function DecryptPassword(NtID As String)
' Grab The Users Encrypted Password
Dim UserID As Integer = GetAppUserID(NtID)
Dim User As Users = Var.db.Web.Users.Find(UserID)
Dim EPassword = User.Password
' Divided the Encrypted Password Into Salt and Actual Password
Dim Salt As String = EPassword.Substring(0, 16) + EPassword.Substring(22, 112)
Dim Password As String = EPassword.Substring(16, 6) + EPassword.Substring(134, EPassword.Length - 134)
Dim DPassword As String = String.Empty
' Try each substring of Salt until password is Decrypted.
Try
If DPassword = String.Empty Then
Dim Security As New Var.Simple3Des(Salt.Substring(0, 32))
DPassword = Security.DecryptData(Password)
End If
Catch ex As Exception
DPassword = String.Empty
End Try
Try
If DPassword = String.Empty Then
Dim Security As New Var.Simple3Des(Salt.Substring(32, 32))
DPassword = Security.DecryptData(Password)
End If
Catch ex As Exception
DPassword = String.Empty
End Try
Try
If DPassword = String.Empty Then
Dim Security As New Var.Simple3Des(Salt.Substring(64, 32))
DPassword = Security.DecryptData(Password)
End If
Catch ex As Exception
DPassword = String.Empty
End Try
Try
If DPassword = String.Empty Then
Dim Security As New Var.Simple3Des(Salt.Substring(96, 32))
DPassword = Security.DecryptData(Password)
End If
Catch ex As Exception
DPassword = String.Empty
End Try
Return DPassword
End Function
My question is
A. Aside from possible perfomance issues, what other dangers does this method pose?
B. Is this overkill, is salting and storing the salt/password like this even necessary?
C. If this is unnecessary what other methods could I use to salt and store salt/password?
Here is a great site that talks about the sort of thing you are interested in: https://crackstation.net/hashing-security.htm. The overall point of what they say is that:
If you are not careful yourself, messing with algorithms that are crafted to be secure can actually reduce their security.
It is overkill because you have to assume that an attacker will get your code before they can crack your database, so they will know your scheme.
Simply storing the hash and the salt should be fine. That is sort of the point of the hash and the salt.
I have used the crackstation page as a general reference on hashing security quite often. I highly recommend reading it as will probably contain plenty of information that you will find relevant and that I omitted here.

Syntax Explanation for SHA-1 Hash Function in Visual Basic

The above is a SHA1 hash function for VB.NET.
Function getSHA1Hash(ByVal strToHash As String) As String
Dim sha1Obj As New Security.Cryptography.SHA1CryptoServiceProvider
Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
bytesToHash = sha1Obj.ComputeHash(bytesToHash)
Dim strResult As String = ""
For Each b As Byte In bytesToHash
strResult += b.ToString("x2")
Next
Return strResult
End Function
Please could someone explain the code above (Visual Basic .NET), specifically the lines below -
bytesToHash = sha1Obj.ComputeHash(bytesToHash)
For Each b As Byte In bytesToHash
strResult += b.ToString("x2")
SHA1 creates a hash (array of bytes) representing the value strToHash. The foreach is just converting this array of bytes into a string.
Create a byte array containing the hash
bytesToHash = sha1Obj.ComputeHash(bytesToHash)
Loop through each byte just created
For Each b As Byte In bytesToHash
Append to the string the hex value of each byte
strResult += b.ToString("x2")
See this for into on hex format of ToString: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#XFormatString

VB Type setting for a SHA512 hash

I have the following function for generating sha512 hashs. The hash is generated successfully, but is causing this error when the resulting string is passed to other functions:
Input string was not in a correct format
When debugged the variable holding the returned hash (set as string) is empty. I have tried changing the type to int, int64 and byte (array and standard variable) in the function and in the calling code, which causes various other errors. How can I change the datatype correctly to solve this?
Function create_hash(ByVal password, ByVal salt)
Dim salty As String = password & salt
'convert salty password to binary to feed into hash function
Dim encText As New System.Text.UTF8Encoding()
Dim btText() As Byte
btText = encText.GetBytes(salty)
'Dim data(btText) As Byte
'create password hash
Dim result() As Byte
Dim shaM As New SHA512Managed()
result = shaM.ComputeHash(btText)
Dim return_result As String
For Each Item As Integer In result
return_result = return_result & Item
Next
Return return_result
End Function
Calling code:
Dim i_h_pass As String
Dim i_pass As String = pass.Text
'handle password generation (matching passwords checked at validation)
Dim newHash = New hashing
Dim salt As String = Convert.ToString(newHash.create_salt)
i_h_pass = Convert.ToString(newHash.create_hash(i_pass, salt))
edit:
the create_salt function has also been checked - it works perfectly and returns a random integer, returned as string for conveince
Fixed with:
Function create_hash(ByVal password, ByVal salt)
Dim salty As String = password & salt
'convert salty password to binary to feed into hash function
Dim encText As New System.Text.UTF8Encoding()
Dim btText() As Byte
btText = encText.GetBytes(salty)
'Dim data(btText) As Byte
'create password hash
Dim result() As Byte
Dim shaM As New SHA512Managed()
result = shaM.ComputeHash(btText)
Dim return_result As String = BitConverter.ToString(result)
Return return_result
End Function
Dim return_result As String = BitConverter.ToString(result)
Being the change