I'm using VB.NET 2010.
One of my lines of code is:
Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox_AccessCode.Text, "MD5"))
But FormsAuthentication is underlined and the error reads 'FormsAuthentication' is not declared. I've ensured that the System.Web.Security namespace is imported, yet I still receive the message.
Any ideas?
Thank you.
FormsAuthentication forms part of the System.Web that is used in asp.net and is not accessibly through Win Forms. Not entirely sure if you will be able to import the dll and use it that way, I doubt it...
If you just want to hash a md5 string you can do below:
new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(TextBox_AccessCode.Text);
x.ComputeHash(bs);
Thanks to TBohnen.jnr, I found that Forms Authentication is not a part of Windows Forms via VB.NET. I ended up using the following code to generate an MD5 hash:
Public Shared Function MD5(ByVal str As String) As String
Dim provider As MD5CryptoServiceProvider
Dim bytValue() As Byte
Dim bytHash() As Byte
Dim strOutput As String = ""
Dim i As Integer
provider = New MD5CryptoServiceProvider()
bytValue = System.Text.Encoding.UTF8.GetBytes(str)
bytHash = provider.ComputeHash(bytValue)
provider.Clear()
For i = 0 To bytHash.Length - 1
strOutput &= bytHash(i).ToString("x").PadLeft(2, "0")
Next
Return strOutput
End Function
Related
I am trying to build an application where security and encryption are a high concern.
I am using Visual Studio 2022 and VB.NET 6.0 (I searched for 3 days now and couldn't find a suitable solution, all that I found is related to a different version of .NET and NOT Visual Studio 2022)
UPDATE: 16/5/2022
I updated my question to be more related to what I really need; which is hashing the password.
Thank you
This solution worked for me like charm:
Imports System.Security.Cryptography
Imports System.Text
Public Module hashing
Public Function PWDhash(ByVal password As String)
Using sha512Hash As SHA512 = SHA512.Create()
Return GetHash(sha512Hash, password)
End Using
End Function
Private Function GetHash(ByVal hashAlgorithm As HashAlgorithm, ByVal input As String) As String
' Convert the input string to a byte array and compute the hash.
Dim data As Byte() = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input))
' Create a new Stringbuilder to collect the bytes
' and create a string.
Dim sBuilder As New StringBuilder()
' Loop through each byte of the hashed data
' and format each one as a hexadecimal string.
For i As Integer = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next
' Return the hexadecimal string.
Return sBuilder.ToString()
End Function
' Verify a hash against a string.
Public Function VerifyHash(hashAlgorithm As HashAlgorithm, input As String, hash As String) As Boolean
' Hash the input.
Dim hashOfInput As String = GetHash(hashAlgorithm, input)
' Create a StringComparer an compare the hashes.
Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
Return comparer.Compare(hashOfInput, hash) = 0
End Function
End Module
This is how to hash:
Dim HashedPWD As String = PWDhash("password here")
This is how to verify:
Dim IsPWDCorrect As Boolean = VerifyHash(sha512Hash, "password here", "password hash from DB")
I also created a function to force user to choose a complex password.
It works on VB.Net Core 6.0
The length of the hash is 128 Byte.
This is an example output:
708ed38ae70f96bc7dcb58515ab328614eaf3b41402de0c50e60ba0f56be5efc6f6daf0b226ec238c3dcaff182e466a1e12df1cadd4e62e6a8c197355b1edc4e
I'm setting up a Login Form on Visual Basic .Net. I would like to have this database hosted over the internet, so people can connect wherever they are.
The trouble is, security. If I have a username and password in my code, I can easily be hacked, and my program will be cracked.
Is there any way to have a token that I can use instead of a password, that can only be accessed in through the program itself?
This is my code:
Dim connection As New MySqlConnection("datasource=localhost;port-3306;username;whatever;password=whatever;database=whatever")
And this is something like what I'm looking for:
Dim connection As New MySqlConnection("token=aFjiwqMF93JmHSazhH")
If so, how would I do this, and where would I get the database token and link from?
Anyone able to crack your program, will more likely have the knowledge to crack into MySQL too... I know, it's not an answer, I spent many weeks trying to secure my programs against similar, however, I then thought 'Why...?'
That being said, If you really need to keep your source code under wraps and passwords removed, how about loading the connection string from a text file somewhere?
Simple encryption see system.security.cryptography
I have just looked up my old code for encrypting strings simply, you can have a look at this
Imports System.Security.Cryptography
Imports System.Net
Public NotInheritable Class Encryptorr
Public TDS As New TripleDESCryptoServiceProvider
Private Function EncHash(ByVal key As String, ByVal length As Integer) As Byte()
Dim enc_Sha1 As New SHA1CryptoServiceProvider
Dim keyBytes() As Byte =
System.Text.Encoding.Unicode.GetBytes(key)
Dim hash() As Byte = enc_Sha1.ComputeHash(keyBytes)
ReDim Preserve hash(length - 1)
Return hash
End Function
Sub New(ByVal key As String)
TDS.Key = EncHash(key, TDS.KeySize \ 8)
TDS.IV = EncHash("", TDS.BlockSize \ 8)
End Sub
Public Function EncryptData(ByVal plaintext As String) As String
Dim Strbytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext)
Dim memStr As New System.IO.MemoryStream
Dim encStream As New CryptoStream(memStr, TDS.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
encStream.Write(Strbytes, 0, Strbytes.Length)
encStream.FlushFinalBlock()
Return Convert.ToBase64String(memStr.ToArray)
End Function
Public Function DecryptData(ByVal encryptedtext As String) As String
Try
Dim enc_Bytes() As Byte = Convert.FromBase64String(encryptedtext)
Dim mem_Str As New System.IO.MemoryStream
Dim decStream As New CryptoStream(mem_Str, TDS.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
decStream.Write(enc_Bytes, 0, enc_Bytes.Length)
decStream.FlushFinalBlock()
Return System.Text.Encoding.Unicode.GetString(mem_Str.ToArray)
Catch ex As Exception
Return "Decryption Failed"
End Try
End Function
End Class
Call with
Public Sub TestMe()
Dim encr As Encryptorr = New Encryptorr("AlovelyLong463728KeytoEncryptwith")
Dim encrytedstr As String = encr.EncryptData(textbox1.text)
Textbox2.text = encrytedstr
Dim decry As Encryptorr = New Encryptorr("AlovelyLong463728KeytoEncryptwith")
Dim decryptedtext As String = decry.DecryptData(Textbox2.text)
Textbox3.text = decryptedtext
End Sub
You can then encrypt and decrypt strings read from text files, although back to my original point. If someone can gain access to the program code, they can also work out the decryption too... :(
Still food for thought! Good luck
Update--
Just to add, you could always create the encrytped string, use that as a global variable and the decryt function to pass directly as your connection string. This means isnstead of saving the username and password in a text file, you just use Public Shared Constr as String = fhdasjifhn32437289cj (or whatever the encrypted string is) and the connection would be Dim Con as MySQLConnection = new MySQLConnection(DecryptMyStr(Constr)) with DecryptMyStr being the decrypt function
I have created a dll in VB.Net that is used in a Visual Foxpro application. Recently I added a few functions to help in sanitizing data and clearing input from a user-control and re-built the project. I am currently using Regasm to register the dll's and this seems to work fine. However when i register the dll, the new functionality does not show, making it seem like one is still using the old, previously registered dll. Is there something i'm not doing right?
Here's an excerpt of the code.
<ClassInterface(ClassInterfaceType.AutoDispatch), ProgId("LPFPasserelle.FicheEtablissement")>
Public Class FicheEtablissement
Private mCreateInstitution As New CreateInstitution
<ComRegisterFunction()>
Public Shared Sub RegisterClass(ByVal key As String)
Dim sb As StringBuilder = New StringBuilder(key)
sb.Replace("HKEY_CLASSES_ROOT\", "")
'// Open the CLSID\{guid} key for write access
Dim k As RegistryKey = Registry.ClassesRoot.OpenSubKey(sb.ToString(), True)
Dim ctrl As RegistryKey = k.CreateSubKey("Control")
ctrl.Close()
'// Next create the CodeBase entry - needed if not string named and GACced.
Dim inprocServer32 As RegistryKey = k.OpenSubKey("InprocServer32", True)
inprocServer32.SetValue("CodeBase", Assembly.GetExecutingAssembly().CodeBase)
inprocServer32.Close()
k.Close()
End Sub
<ComUnregisterFunction()>
Public Shared Sub UnregisterClass(ByVal key As String)
Dim sb As StringBuilder = New StringBuilder(key)
sb.Replace("HKEY_CLASSES_ROOT\", "")
'// Open HKCR\CLSID\{guid} for write access
Dim k As RegistryKey = Registry.ClassesRoot.OpenSubKey(sb.ToString(), True)
'// Delete the 'Control' key, but don't throw an exception if it does not exist
If k Is Nothing Then
Return
End If
k.DeleteSubKey("Control", False)
'// Next open up InprocServer32
Dim inprocServer32 As RegistryKey = k.OpenSubKey("InprocServer32", True)
'// And delete the CodeBase key, again not throwing if missing
inprocServer32.DeleteSubKey("CodeBase", False)
'// Finally close the main key
inprocServer32.Close()
k.Close()
End Sub
The function for sanitizing string data that I added is below.
Function SanitizeStringData(ByVal StringToSanitize As String)
Dim mSanitizedString As String = String.Empty
mSanitizedString = Trim(StringToSanitize)
If Trim(StringToSanitize).Contains("'") Then
mSanitizedString = Trim(StringToSanitize).Replace("'", "''")
End If
Return mSanitizedString
End Function
Not sure about your sanitizing dll/COM issue, but for your sanitize string, I don't know why you are not just using VFP's function STRTRAN()
someString = [What's goin' on]
? STRTRAN( someString, "'", "''" )
will result in
What''s goin'' on
Help on StrTran() function
Another cool one is CHRTRAN() and has a wide range of benefits from stripping invalid characters from strings to a pseudo encryption by replacing every character in a string to something else...
I'm in the process of writing a little app for our SQL developers to allow them to create labels with TFS for easy code deployment, the trouble is the .ssmssqlproj files are being added to the label when ever i create one. I've added a sub to loop through and unlabel these file but i just will not work. code below
Public Sub UnlabelItem()
Dim returnValue As LabelResult()
Dim labelName As String = "1208-2210"
Dim labelScope As String = "$/"
Dim version As VersionSpec = New LabelVersionSpec(labelName, labelScope)
Dim path As String = "$/FEPI/Database/FEPI/000 Pre Tasks.ssmssqlproj"
Dim recursion As RecursionType = RecursionType.None
Dim itemspec As ItemSpec = New ItemSpec(path, recursion)
returnValue = sourceControl.UnlabelItem(labelName, labelScope, itemspec, version)
End Sub
this is a test Sub just to get it working and this is the error i get
Value of type 'Microsoft.TeamFoundation.VersionControl.Client.ItemSpec' cannot be converted to '1-dimensional array of Microsoft.TeamFoundation.VersionControl.Client.ItemSpec'
HAs anybody had any luck with the unlabel command?
Matt
I have managed to successfully connect remotely to the MySQL database for my Joomla! 1.5 website using MySqlConnector in Visual Basic .NET 2010.
Now I am trying to authenticate a user's password from values submitted in a simple form to those retrieved from a MySQL query.
I found a useful thread on forums.joomla.org titled "Joomla password MD5 & VB.NET MD5", but the code snippets there produce the incorrect hash.
Here is another useful Joomla Forums thread as to how passwords are encrypted (using MD5 hash and "salt") in the Joomla DB.
Here is a modified version of the code:
Imports System.Text
Imports System.Security.Cryptography
...
Private Function JoomlaUserAuth(ByVal Password As String, ByVal EncryptedPassword As String) As Boolean
'HashedPassword:Salt = value from Joomla DB
Dim Values() As String = Split(EncryptedPassword, ":")
Dim HashedPassword As String = Values(0)
Dim Salt As String = Values(1)
Dim NewHashedPassword As String = GetHash(Password & Salt)
Return NewHashedPassword.Equals(HashedPassword)
End Function
Private Function GetHash(ByVal StringToHash As String) As String
Dim md5 As New MD5CryptoServiceProvider()
Dim encoder As New UTF7Encoding()
Dim encStringBytes As [Byte]()
encStringBytes = encoder.GetBytes(StringToHash)
encStringBytes = md5.ComputeHash(encStringBytes)
Dim strHex As String = String.Empty
For Each B As Byte In encStringBytes
strHex &= String.Format("{0:x2}", B)
Next
Return strHex
End Function
The result is that "NewHashedPassword" and "HashedPassword" are very different using the correct password/DB encrypted password combination. Any ideas?
To get the correct hash for the user password you should input the password twice, something like:
Dim NewHashedPassword As String = GetHash(Password & Password & Salt)