Hashing or Encoding functions in VB.NET - vb.net

I have the following functions in a VB script:
Function DecryptSHA1(ByVal strOriginalString As String) As String
If strOriginalString = "" Then Return ""
Dim dEC_data() As Byte = Convert.FromBase64String(strOriginalString)
Dim dEC_Str As String = ASCIIEncoding.ASCII.GetString(dEC_data)
DecryptSHA1 = dEC_Str
End Function
Function EncryptSHA1(ByVal strOriginalString As String) As String
If strOriginalString = "" Then Return ""
Dim shaM As New SHA1Managed
Convert.ToBase64String(shaM.ComputeHash(Encoding.ASCII.GetBytes(strOriginalString)))
Dim eNC_data() As Byte = ASCIIEncoding.ASCII.GetBytes(strOriginalString)
Dim eNC_str As String = Convert.ToBase64String(eNC_data)
EncryptSHA1 = eNC_str
End Function
I don't code in VB but as much as I can see the functions have nothing to do with encrypting SHA1 but rater Base64 encoding and decoding. Am I wrong? The only thing that can make me think about hashing is the Dim shaM As New SHA1Managed line in the EncryptSHA1() function but the DecryptSHA1() function doesn't use it anymore. Are these simple Base64 encode/decode functions or more?

The only thing these functions do is converting to and from base64.
In the EncryptSHA1 function there is some SHA1 hashing code, but it is not actually used.
So there is no hashing nor encryption going on which makes the functions quite confusing.

Related

Decode using available method for encoding in VB

I have this method
Public Shared Function HashPassword(ByVal password As String) As String
Dim algorithm As HashAlgorithm
algorithm = SHA1.Create
Dim data As Byte() = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password))
Dim HashedPassword As String = ""
Dim i As Integer = 0
Do While i < data.Length
HashedPassword &= data(i).ToString("x2").ToLowerInvariant()
i += 1
Loop
Return HashedPassword
End Function
How can I decode a string which has been encoded by this function?
A hash is a one way so you dont decrypt them. Instead, compare the new input value to the stored hash to verify. If you want to encrypt/decrypt data (not the best way to protect passwords), then you need to encrypt, not hash.
But there may be a problem with your method: the result is usually converted to base64 for storing/saving. A hex string might work (never tried) but there is a built in way for this:
Public Shared Function HashPassword(password As String) As String
Dim algorithm As HashAlgorithm
algorithm = SHA1.Create
Dim data As Byte() = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password))
Return Convert.ToBase64String(data)
End Function
So, new user registration would be something like:
hashedPW = HashPassword(thePWText)
To check it later:
thisPW = HashPassword(PWInput)
If thisPW = hashedPW Then
' user knows the PW
Else
' wrong password
End If

encrypt a string using SHA512

Here 's my code and I have no idea why it produces a weird code in the console
(output is "b5?2???p?????'5???.?H???Kun???a??\??d??+\??%??A)?_???j?" without the quotes)
Private Sub TestSHA512()
Dim key As String = "635357773463315343"
Dim pass As String = "somepasswd"
Dim enc As System.Text.Encoding = New System.Text.ASCIIEncoding
Dim keyBytes() As Byte = enc.GetBytes(key)
Dim passBytes() As Byte = enc.GetBytes(pass)
Dim SHA As New HMACSHA512(keyBytes)
Dim resultBytes() As Byte = SHA.ComputeHash(passBytes)
Console.WriteLine(enc.GetString(resultBytes))
Console.WriteLine(enc.GetString(SHA.Hash)) 'same...
End Sub
First, SHA512 is a hash algorithm, not an encryption scheme, so if you're trying to encrypt then SHA512 isn't the way to do it. You'd need to look at an encryption class, such as AesManaged.
ComputeHash gives you the computed hash as a byte array. You're using ASCIIEncoding.GetString to convert that into a string, but not every byte is a printable ASCII character. That's why you're seeing the ??? characters in your console output.
If you're asking how to display the hash output as a printable string, use Convert.ToBase64String, which will convert the byte array into a string using base64 encoding. If you were expecting it in hexadecimal, you can loop through the byte array and print the Hex() value of each byte.

build/check hash value for file

I'm having hard time with this one. Can someone either point me in the right direction for checking/building hash codes for an uploaded file or else tell me what I'm doing wrong with the code below?
getFileSHA256(softwareUpload.PostedFile) 'Line that calls the function includes a reference to an uploaded file
Private Function getFileSHA256(ByVal theFile As Web.HttpPostedFile) As String
Dim SHA256CSP As New SHA256Managed()
Dim byteHash() As Byte = SHA256CSP.ComputeHash(theFile.InputStream)
Return ByteArrayToString(byteHash)
End Function
Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
Dim sb As New System.Text.StringBuilder(arrInput.Length * 2)
For i As Integer = 0 To arrInput.Length - 1
sb.Append(arrInput(i).ToString("X2"))
Next
Return sb.ToString().ToLower
End Function
I should add that the function works, but the return does not match other programs' sha256 values.
EDIT ------
There are two other functions that I'm using in my code. SHA1 gets the same kind of results as the SHA256; the results do not match trusted sources.
However, the MD5 works as expected.
Private Function getFileSHA1(ByVal theFile As Web.HttpPostedFile) As String
Dim SHA1CSP As New SHA1CryptoServiceProvider()
Dim byteHash() As Byte = SHA1CSP.ComputeHash(theFile.InputStream)
Return ByteArrayToString(byteHash)
End Function
Private Function getFileMd5(ByVal theFile As Web.HttpPostedFile) As String
Dim Md5CSP As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim byteHash() As Byte = Md5CSP.ComputeHash(theFile.InputStream)
Return ByteArrayToString(byteHash)
End Function
I plan to consolidate these functions once I know they are working as expected.
The only difference between these is that MD5 is using "MD5CryptoServiceProvider" and it works as expected. SHA1 is also using "SHA1CryptoServiceProvider" but it does not match trusted sources.
I did some testing here, it appears that for text files SHA256Managed works perfectly.
My code is below, I used your implementation of ByteArrayToString:
Sub Main()
Dim s As New SHA256Managed
Dim fileBytes() As Byte = IO.File.ReadAllBytes("s:\sha256.txt")
Dim hash() As Byte = s.ComputeHash(fileBytes)
Dim referenceHash As String = "18ffd9682c5535a2b2798ca51b13e9490df326f185a83fe6e059f8ff47d92105"
Dim calculatedHash As String = ByteArrayToString(hash)
MsgBox(calculatedHash = referenceHash) 'outputs True
End Sub
Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
Dim sb As New System.Text.StringBuilder(arrInput.Length * 2)
For i As Integer = 0 To arrInput.Length - 1
sb.Append(arrInput(i).ToString("X2"))
Next
Return sb.ToString().ToLower
End Function
For testing purposes, I created a file called sha256.txt under S: with the following contents:
my test file
(no trailing spaces or newline)
I got the reference hash value from here, by feeding same data.
Also check this and this - the fact you get non-match could be related to platform and/or implementation of your trusted source, or needing an extra conversion step.

Mixed Encoding to String

I have a string in VB.net that may contain something like the following:
This is a 0x000020AC symbol
This is the UTF-32 encoding for the Euro Symbol according to this article http://www.fileformat.info/info/unicode/char/20ac/index.htm
I'd like to convert this into
This is a € symbol
I've tried using UnicodeEncoding() class in VB.net (Framework 2.0, as I'm modifying a legacy application)
When I use this class to encode, and then decode I still get back the original string.
I expected that the UnicodeEncoding would recognise the already encoded part and not encode it against. But it appears to not be the case.
I'm a little lost now as to how I can convert a mixed encoded string into a normal string.
Background: When saving an Excel spreadsheet as CSV, anything outside of the ascii range gets converted to ?. So my idea is that if I can get my client to search/replace a few characters, such as the Euro symbol, into an encoded string such as 0x000020AC. Then I was hoping to convert those encoded parts back into the real symbols before I insert to a SQL database.
I've tried a function such as
Public Function Decode(ByVal s As String) As String
Dim uni As New UnicodeEncoding()
Dim encodedBytes As Byte() = uni.GetBytes(s)
Dim output As String = ""
output = uni.GetString(encodedBytes)
Return output
End Function
Which was based on the examples on the MSDN at http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.aspx
It could be that I have a complete mis-understanding of how this works in VB.net. In C# I can simply use escaped characters such as "\u20AC". But no such thing exists in VB.net.
Based on advice from Heinzi I implemented a Regex.Replace method using the following code, this appear to work for my examples.
Public Function Decode(ByVal s As String) As String
Dim output As String = ""
Dim sRegex As String = "0x[0-9a-zA-Z]{8}"
Dim r As Regex = New Regex(sRegex)
Dim myEvaluator As MatchEvaluator = New MatchEvaluator(AddressOf HexToString)
output = r.Replace(s, myEvaluator)
Return output
End Function
Public Function HexToString(ByVal hexString As Match) As String
Dim uni As New UnicodeEncoding(True, True)
Dim input As String = hexString.ToString
input = input.Substring(2)
input = input.TrimStart("0"c)
Dim output As String
Dim length As Integer = input.Length
Dim upperBound As Integer = length \ 2
If length Mod 2 = 0 Then
upperBound -= 1
Else
input = "0" & input
End If
Dim bytes(upperBound) As Byte
For i As Integer = 0 To upperBound
bytes(i) = Convert.ToByte(input.Substring(i * 2, 2), 16)
Next
output = uni.GetString(bytes)
Return output
End Function
Have you tried:
Public Function Decode(Byval Coded as string) as string
Return StrConv(Coded, vbUnicode)
End Function
Also, your function is invalid. It takes s as an argument, does a load of stuff and then outputs the s that was put into it instead of the stuff that was processed within it.

sha-1 creation in vb .net 3.5

I'm having a great deal of difficulty finding a function or sub for vb (not C) that provides an easy way to convert a given string into a sha-1 (or sha512 ideally) hash.
If someone could provide a function in VB, it'd be extremely helpful.
Nearest attempt:
Function create_hash(ByVal password, ByVal salt)
Dim input As [Char]() = "string to hash".ToCharArray()
Dim secret As New SecureString()
For idx As Integer = 0 To input.Length - 1
secret.AppendChar(input(idx))
Next SecurePassword.MakeReadOnly()
Dim pBStr As IntPtr = Marshal.SecureStringToBSTR(secret)
Dim output As String = Marshal.PtrToStringBSTR(pBStr)
Marshal.FreeBSTR(pBStr)
Dim sha As SHA512 = New SHA512Managed()
Dim result As Byte() = sha.ComputeHash(Encoding.UTF8.GetBytes(output))
Return result
End Function
But this causes visual stuido to blue underline SecurePassword and Marshal at evey use. These are marked as undeclared variables, but declaring them causes other problems which I can't find a way to solve.
Take a look at the documentation for the System.Security.Cryptography.SHA512 class.
Dim data(DATA_SIZE) As Byte
Dim result() As Byte
Dim shaM As New SHA512Managed()
result = shaM.ComputeHash(data)
Like this (ignoring the salting you are doing at the top):
Function create_hash(ByVal password, ByVal salt) As Byte()
Dim sha As SHA512 = New SHA512Managed()
Dim result As Byte() = sha.ComputeHash(Encoding.UTF8.GetBytes(password & salt))
Return result
End Function