VB.Net and phpMyAdmin: How to connect to phpMyAdmin SQL server without needing a Username or Password? - vb.net

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

Related

Decrypting and Copying Contents of Encrypted Text File to MemoryStream

I'm trying to copy the encrypted contents of a text file into a memory stream and then decrypt and copy those contents into a new memory stream. When I reach the code where the copy occurs I get a Invalid Data error on debug.
This is the block of code I got:
Function DecryptFile(ByVal sInputFilename As String, ByVal sKey As String) As Byte()
Dim DES As New DESCryptoServiceProvider()
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()
Dim encryptedByteArray() As Byte
encryptedByteArray = File.ReadAllBytes(sInputFilename)
Dim encryptedMS As MemoryStream = New MemoryStream(encryptedByteArray)
Dim cryptostreamDecr As New CryptoStream(encryptedMS, desdecrypt, CryptoStreamMode.Read)
Dim decryptedMS As MemoryStream = New MemoryStream()
cryptostreamDecr.CopyTo(decryptedMS) 'Error occurs here
cryptostreamDecr.Close()
Return decryptedMS.ToArray()
End Function
I'm following examples I've found scattered around the web and from what I've read, this code should work...
May anyone explain to me what am I doing wrong?
Here's an example to encrypt/decrypt a string and a file using a Key without explicitly providing an Initialization Vector (so yo don't need to store and retrieve it to decrypt encrypted data).
The Encryption provider I'm using here is TripleDESCryptoServiceProvider.
If you need to use a DES provider, it's exactly the same thing, you just need to change TripleDESCryptoServiceProvider to DESCryptoServiceProvider.
But, as you can read in the Docs, better move to the AesCryptoServiceProvider, if/when possible.
The Initialization Vector (IV) is calculated based on the Key specified and it's the same Hashed value if the Key to Decrypt the data is the same as the Key used to Encrypt it.
In this case, you lose some security, but you don't need to store either the Key or the IV (if the Key is provided by a User, who's responsible for protecting the Key).
The Mode is left to its default: CipherMode.CBC.
The Padding Mode to its default: PaddingMode.PKCS7.
Encrypt and decrypt a sting to and from a Base64String:
Dim enc3Des As New TripleDesEncryptor("MyFancyKey")
Dim inputString = "Some fancy string to be encoded to a Base64 string"
Dim encodedB64 = enc3Des.EncryptStringToBase64(inputString)
Dim decoded64 = enc3Des.DecryptBase64String(encoded64)
To encrypt a file, provide the path to the Source file, then save the bytes returned by the Encryption method to a destination file:
Dim enc3Des As New TripleDesEncryptor("MyFancyKey")
Dim plainTextFilePath = [Source file Path]
Dim encryptedFilePath = [Encrypted file Path]
Dim encodedBytes = enc3Des.EncryptFile(plainTextFilePath)
File.WriteAllBytes(encryptedFilePath, encodedBytes)
You can of course decrypt the File when required, using the same Key:
Dim encryptedFilePath = [Encrypted file Path]
Dim decryptedFilePath = [Decrypted file Path]
Dim enc3Des2 As New TripleDesEncryptor("MyFancyKey")
Dim decodedBytes = enc3Des2.DecryptFile(encryptedFilePath)
File.WriteAllBytes(decryptedFilePath, decodedBytes)
The TripleDesEncryptor helper class:
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public NotInheritable Class TripleDesEncryptor
Private tripleDesProvider As New TripleDESCryptoServiceProvider()
Sub New(key As String)
tripleDesProvider.Key = GetKeyHash(key, tripleDesProvider.LegalKeySizes(0).MaxSize \ 8)
tripleDesProvider.IV = GetKeyHash(key, tripleDesProvider.LegalBlockSizes(0).MaxSize \ 8)
End Sub
Public Function EncryptStringToBase64(inputString As String) As String
Dim dataBytes As Byte() = Encoding.Unicode.GetBytes(inputString)
Return Convert.ToBase64String(Encrypt(dataBytes))
End Function
Public Function EncryptFile(fileName As String) As Byte()
Dim dataBytes As Byte() = File.ReadAllBytes(fileName)
Return Encrypt(dataBytes)
End Function
Private Function Encrypt(dataBytes As Byte()) As Byte()
Using ms As New MemoryStream(),
encStream As New CryptoStream(ms, tripleDesProvider.CreateEncryptor(), CryptoStreamMode.Write)
encStream.Write(dataBytes, 0, dataBytes.Length)
encStream.FlushFinalBlock()
Return ms.ToArray()
End Using
End Function
Public Function DecryptBase64String(base64String As String) As String
Dim dataBytes As Byte() = Convert.FromBase64String(base64String)
Return Encoding.Unicode.GetString(Decrypt(dataBytes))
End Function
Public Function DecryptFile(fileName As String) As Byte()
Dim dataBytes As Byte() = File.ReadAllBytes(fileName)
Return Decrypt(dataBytes)
End Function
Private Function Decrypt(encryptedData As Byte()) As Byte()
Using ms As New MemoryStream(),
decStream As New CryptoStream(ms, tripleDesProvider.CreateDecryptor(), CryptoStreamMode.Write)
decStream.Write(encryptedData, 0, encryptedData.Length)
decStream.FlushFinalBlock()
Return ms.ToArray()
End Using
End Function
Private Function GetKeyHash(key As String, length As Integer) As Byte()
Using sha1 = SHA1.Create()
Dim varHash As Byte() = New Byte(length - 1) {}
Dim keyBytes As Byte() = Encoding.Unicode.GetBytes(key)
Dim hash As Byte() = sha1.ComputeHash(keyBytes).Take(length).ToArray()
Array.Copy(hash, 0, varHash, 0, hash.Length)
hash = Nothing
keyBytes = Nothing
Return varHash
End Using
End Function
End Class
Perhaps I should have explained what I'm trying to achieve in the first place.
I have a text file that has over 1000 keywords. The vb.net application will, at some point, read these keywords from the text file to do something with them.
Now, my approach here is to not let prying eyes to edit the text file, changing the key words or even knowing which keywords are on it.
Therefor, what I did was encrypt the keywords and save the encrypted content into a new file and deleted the unencrypted file, so that this way I don't need to care about people checking the encrypted file, because it's just gibberish.
According to Jimi's explanation, posted before, I see now that in order to decrypt the file, I need the same IV I used for encrypting the previous file.
So the only way I see for this to be possible without having an unencrypted file 'lying around' is to store the IV secret key within the application's settings, correct?

How to encrypt and decrypt string to base64?

Good day to all, I am new to vb.net programming. I wanted to encrypt and decrypt user passwords, I came up with the code below.
Imports System.Security.Cryptography
Imports System.Text
Public Class UPdatePass
Dim DES As New TripleDESCryptoServiceProvider
Dim MD5 As New MD5CryptoServiceProvider
Function Encrypt(StringInput As String, Key As String) As String
DES.Key = MD5Hash(Key)
DES.Mode = CipherMode.ECB
Dim buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(StringInput)
Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
End Function
Function Decrypt(EncryptedString As String, Key As String) As String
DES.Key = MD5Hash(Key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = Convert.FromBase64String(EncryptedString)
Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
Function MD5Hash(value As String) As Byte()
Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function
End Class
When I execute the code and decrypt, I get this error message.
An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: Length of the data to decrypt is invalid.
I hope anyone can help me with this. Thank you!
Your code works fine for me. check if the key you are entering for encryption is the same as the decryption

Getting variable encryption results with VB.Net and DES

I'm working on an semi-internal encryption process for somewhat sensitive information. Email addresses and the like. I'm working with a few other developers at some sister companies on the project, and the requirements are that everyone's encryption can talk to everyone else's. We use a global password, encrypt and decrypt information onsite, and that's about it.
My problem is that my encryption procedure, while matching theirs, is giving me variable results. I'm currently polling our SQL server for the strings to be encrypted in question, iterating through the array of results, and updating the server with the encrypted strings.
The problem is that the first string is always different from all subsequent strings, and isn't recognized as valid by the testing software we're supposed to be basing our solution off of. The second and all subsequent strings come through just fine.
Example:
test#test.com - BrPURPlWW7+VYrR5puJ/JHXoIp/MV5WR
test#test.com - BrPURPlWW79h+n4Tgot0xRmM7SdWQQsy
test#test.com - BrPURPlWW79h+n4Tgot0xRmM7SdWQQsy
I can't quite figure out what's going on, because I can encrypt and decrypt back and forth on my own machine with no issues. Any advice would be lovely.
My encryption function follows:
Private TripleDES As New DESCryptoServiceProvider
Sub New(ByVal key As String)
Dim ivHash(), keyHash() As Byte
keyHash = System.Text.Encoding.UTF8.GetBytes(key)
ReDim Preserve keyHash(7)
TripleDES.Key = keyHash
ivHash = System.Text.Encoding.UTF8.GetBytes(String.Empty)
ReDim Preserve ivHash(7)
TripleDES.IV = ivHash
End Sub
Public Function EncryptData(ByVal Plaintext As String) As String
Dim PlaintextBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(Plaintext)
Dim ms As New System.IO.MemoryStream
Dim encStream As New CryptoStream(ms, TripleDES.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
TripleDES.Mode = CipherMode.ECB
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)
TripleDES.Mode = CipherMode.ECB
decStream.Write(EncryptedBytes, 0, EncryptedBytes.Length)
decStream.FlushFinalBlock()
Return System.Text.Encoding.UTF8.GetString(ms.ToArray)
End Function
You are setting TripleDES.Mode = CipherMode.ECB after you have called TripleDES.CreateEncryptor(), so the first encryption is using the default value of CipherMode.CBC. Since TripleDES is reused, after the first call to EncryptData its Mode is set correctly.
Move TripleDES.Mode = CipherMode.ECB into New and it should work consistently.

Hash with MD5 in VB.NET

So, I got a bit of a problem here, I got a database, a login and a registration, all in different classes, now I need to hash the password in the database and read it out again when logging in, but I don't know how to handle this, I already searched a lot but couldn't find anything useful.
Here is my login class
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlServerCe
Public Class Login
Inherits System.Web.UI.Page
Private Sub LSend_Click(sender As Object, e As System.EventArgs) Handles LSend.Click
If Bibliothek.EntryExists(LNAME.Text, "Username") = False Then
LNAMELBL.Text = "Name oder Passwort Falsch."
Exit Sub
End If
If Bibliothek.EntryExists(LPW.Text, "Passwort") = False Then
LNAMELBL.Text = "Name oder Passwort Falsch."
Exit Sub
End If
Dim UserN As String = LNAME.Text
Session("Admin") = Bibliothek.GetValueBool(UserN, "IsAdmin")
Session("USERNA") = Bibliothek.GetValueBool(UserN, "Username")
Response.Redirect("/TSL/Home.aspx")
End Sub
Private Sub REG_Click(sender As Object, e As System.EventArgs) Handles REG.Click
Response.Redirect("/TSL/Registrierung.aspx")
End Sub
End Class
It is important to note that MD5 is no longer considered a good way to hash data you wish to protect. See wikipedia for a discussion of the vulnerabilities.
See this answer for hashing using SHA.
For passwords, you'd save the hash of the user's PW to the DB. Because it is one-way (you cannot easily get the original value back from the hash), this prevents someone like a janitor or customer service rep from being able to see the actual passwords in the database.
Imports System.Security.Cryptography
Imports System.Text
Shared Function GetHash(theInput As String) As String
Using hasher As MD5 = MD5.Create() ' create hash object
' Convert to byte array and get hash
Dim dbytes As Byte() =
hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput))
' sb to create string from bytes
Dim sBuilder As New StringBuilder()
' convert byte data to hex string
For n As Integer = 0 To dbytes.Length - 1
sBuilder.Append(dbytes(n).ToString("X2"))
Next n
Return sBuilder.ToString()
End Using
End Function
Depending on how you want to save it, rather than a using StringBuilder to create a hex string, you can use Convert.ToBase64String():
Return Convert.ToBase64String(dbytes)
' MyWeakPassword hashed:
' to hex: DB28F1BE20A407398171295DD0D191E2
' to Base64: 2yjxviCkBzmBcSld0NGR4g==
Hashing should be done with salt. This is data added to the hash to make the result less predictable (there are dictionaries of the hashed results of common PW such as "password"; salt changes the outcome):
Shared Function GetHash(theInput As String, theSalt As String) As String
...
hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput & theSalt))
Salt should be created using the Cryptographic random number generator as shown in the SHA Version. Convert the salt to text (hex or Base64) then combine with the PW to get the PW hash.
To check/compare a user's entry, simply hash the input and compare it to the hash stored in the database, using the same Salt (which means the Salt needs to be saved):
Shared Function CheckHash(hashedStr As String, newInput As String) As Boolean
' get the hash value of user input:
Dim newHash As String = GetHash(newInput & dbSalt)
' return comparison
Return String.Compare(newHash, hashedStr, InvariantCultureIgnoreCase)
End Function
As written, the GetHash function is intended to be used from something like a CryptoTools Class. Since it is Shared/Static the class need not be instanced:
thisHash = CryptoTools.GetHash(strToHash)
Note: Hashing is case sensitive, so foobar will result in a different hash than FooBar or FOOBAR. To create a case insensitive system, convert the original string (such as a password) to lowercase before you compute the MD5 hash value to be saved, and do the same for the value they later enter:
' ToLowerInvariant allows for foreign char sets
Dim str As String = PWTextBox.Text.ToLowerInvariant
If CheckHash(dbHashedValue, str) Then
' okie dokie
Else
' failed
End If
MD5 Convertion
Dim [source] As String = password_text_box.text
Using md5Hash As MD5 = MD5.Create()
Dim hash As String = GetMd5Hash(md5Hash, source)
2, Insert Name and hash into database
3, Validation
During login take MD5 of password again
run sql query
Select name,password from table where Login ='" & username & "' and
Password ='" & md5(user input pass) & "'
if dreader returns value , then valid login else invalid login
Private Function GetHash(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 New StringBuilder
For Each b As Byte In bytesToHash
strResult.Append(b.ToString("x2"))
Next
Return strResult.ToString
End Function
This would be my solution:
Public Sub _Enkripsi()
Dim _DES As New TripleDESCryptoServiceProvider()
Dim _HashMD5 As New MD5CryptoServiceProvider()
_DES.Key = _HashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(PasswordTextBox.Text))
_DES.Mode = CipherMode.ECB
Dim _DESEncrypt As ICryptoTransform = _DES.CreateEncryptor()
Dim _Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(PasswordTextBox.Text)
_Password = Convert.ToBase64String(_DESEncrypt.TransformFinalBlock(_Buffer, 0, _Buffer.Length))
End Sub
Convert String to MD5 Function for Visual Studio Basic 2022
Imports System.Security.Cryptography
Imports System.Text
Function CovertToMD5(retVal As String) As String
Using MD5 = System.Security.Cryptography.MD5.Create()
Return BitConverter.ToString(MD5.ComputeHash(Encoding.Default.GetBytes(retVal))).Replace("-", String.Empty)
End Using
End Function

Joomla Password Authentication in Visual Basic .NET

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)