Hashing gone wrong - vb.net

I'm using the same function to hash values for comparison during login as I am to hash the passwords when users register:
Public Shared Function Compute(ByVal text As String, ByVal algorithm As String, Optional ByVal salt() As Byte = Nothing) As String
If salt Is Nothing Then
Dim saltSize As Integer = 8
salt = New Byte(saltSize - 1) {}
Dim rng As New RNGCryptoServiceProvider
rng.GetNonZeroBytes(salt)
End If
Dim textBytes As Byte() = Encoding.UTF8.GetBytes(text)
Dim saltedTextBytes() As Byte = New Byte(textBytes.Length + salt.Length - 1) {}
For i As Integer = 0 To textBytes.Length - 1
saltedTextBytes(i) = textBytes(i)
Next i
For i As Integer = 0 To salt.Length - 1
saltedTextBytes(textBytes.Length + i) = salt(i)
Next i
Dim hash As HashAlgorithm
If algorithm Is Nothing Then
algorithm = ""
End If
Select Case algorithm.ToUpper
Case "SHA1" : hash = New SHA1Managed
Case "SHA256" : hash = New SHA256Managed
Case "SHA384" : hash = New SHA384Managed
Case "SHA512" : hash = New SHA512Managed
Case Else : hash = New MD5CryptoServiceProvider
End Select
Dim hashBytes As Byte() = hash.ComputeHash(saltedTextBytes)
Dim saltedHash() As Byte = New Byte(hashBytes.Length + salt.Length - 1) {}
For i As Integer = 0 To hashBytes.Length - 1
saltedHash(i) = hashBytes(i)
Next i
For i As Integer = 0 To salt.Length - 1
saltedHash(hashBytes.Length + i) = salt(i)
Next i
Dim hashValue As String = Convert.ToBase64String(saltedHash)
Return Left(hashValue, 36)
End Function
My problem is that when I try to log in on an account whose password was hashed by this function, the hashed values don't match up. I think I'm skipping a step or something.
Here's the code for user account creation:
' The email address needs to be valid
Dim pattern As String = "^(?("")("".+?""#)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])#))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
Dim match As Match = Regex.Match(txtEmail.Text, pattern)
If match.Success Then
'Hash the user's password before entering it into the database.
Dim pass As String = Crypt.Compute(txtPass.Text, "SHA512", Nothing)
' Enter the information from the form into the database.
Dim sql As String = "INSERT INTO Users(Username, Password, EmailAddress) " & _
"VALUES(#User, #Pass, #Email)"
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#User", txtName.Text)
cmd.Parameters.AddWithValue("#Pass", pass)
cmd.Parameters.AddWithValue("#Email", txtEmail.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Else
lblError.Text = "Invalid email address. Please correct."
lblError.ForeColor = Drawing.Color.Red
End If
There are more checks that aren't included here that aren't relevant to my problem.
Here's my user login:
Dim pass As String = Crypt.Compute(txtPass.Text, "SHA512", Nothing)
Dim UserData As New DataSet
Dim UserAdapter As New SqlDataAdapter
UserAdapter.SelectCommand = New SqlCommand("SELECT * FROM Users " & _
"WHERE Username = #User AND Password = #Pass", conn)
UserAdapter.SelectCommand.Parameters.AddWithValue("#User", txtUser.Text)
UserAdapter.SelectCommand.Parameters.AddWithValue("#Pass", pass)
UserAdapter.Fill(UserData)
If UserData.Tables(0).Rows.Count <> 1 Then
lblError.Text = "Invalid username or password."
lblError.ForeColor = Drawing.Color.Red
Session("LoginAttempt") = CInt(Session("LoginAttempt")) + 1
Else
Session("LoggedIn") = True
Response.Redirect("Home.aspx")
End If
As far as I can see, there is no difference in the hashing I've done here.
Does anyone have any ideas?

When you creating an account by inserting into the table, you are using txtName.Text for the username, but when checking the credentials you are using txtUser.Text.
Why are you using a random salt? Doesn't the salt have to be the same for every encryption? I've pasted your code into a new project, and when I run the Compute method twice in a row for the same password, I get two different results... obviously that won't work. Try passing in a salt value instead of Nothing, and use the same salt for creating accounts and comparing login. Here's some sample code that works:
Dim thePass As String = "MyPassword"
Dim theSalt As String = "salt"
Dim pass As String = Compute(thePass, "SHA512", Encoding.UTF8.GetBytes(theSalt))
Console.WriteLine(pass)
Dim pass2 As String = Compute(thePass, "SHA512", Encoding.UTF8.GetBytes(theSalt))
Console.WriteLine(pass2) 'pass and pass2 are identical
Hope this helps!

Unless I'm missing it (not really familiar with the language), you don't store the salt anywhere.
You have to use the same salt you've used when creating the account for the verification.
On a side note: You can either generate a random salt for every user account or use a fixed salt for all accounts. Either method works. The first is theoretically more secure, but if the salt is long enough, both are fine for practical purposes.

Related

Didisoft PGP Decrypt and Verify

I am trying to Decrypt using Didisoft pgp, and running into some issues. I can generate private and public key just fine. I can also Encrypt the file using SignAndEncryptFile function, and it returns the .pgp file just fine. The problem is when I tried to use the DecryptAndVerifyFile function. It returns an exception Wrong Private Key, I have checked so many times, that my public and private key are the same to the one that I use for Encrypting the file, the password that I used is all the same, because I'm just testing it. What did I do Wrong? :(
It only happens when I tried to use public key and private key to encrypt and decrypt it. I managed to do Encrypt and Decrypt before but it only uses the private key.
Public Function GetValue(ByVal FileData As String, ByVal email As String, ByVal password As String) As String
Dim idKey As String = Guid.NewGuid().ToString()
Dim ks As KeyStore = New KeyStore()
Dim keySize As Integer = 1024
'Dim password As String = "12345"
Dim FilePathKey As String
Dim FilePathPublicKey As String
Dim keys As KeyPairInformation() = ks.GetKeys()
' Generate DH/DSS OpenPGP key
ks.GenerateElgamalKeyPair(keySize, email, password)
'idKey = ks(0).KeyId
FilePathKey = Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\", "Coba\" + idKey + ".key")
ks.ExportPrivateKey(FilePathKey, ks(0).KeyId)
Dim sql As New MySqlConnection()
Dim adapter As New MySqlDataAdapter
sql.ConnectionString = "server=localhost;userid=root;database=test"
Dim query As String = "Select public_key from public_key LIMIT 1"
Dim cmd As MySqlCommand
Dim dt As New DataSet()
cmd = New MySqlCommand(query, sql)
sql.Open()
adapter = New MySqlDataAdapter(cmd)
adapter.Fill(dt)
sql.Close()
FilePathPublicKey = Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\PublicKey\", dt.Tables(0).Rows(0).Item(0).ToString + ".key")
If File.Exists(FileData) Then
'Encrypt Data
Dim pgp As New PGPLib()
Dim idData As String = Guid.NewGuid().ToString()
Dim asciiArmor As Boolean = True
Dim withIntegrityCheck As Boolean = True
Dim encryptedOutputFile As String = Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\Coba\", idData + ".pgp")
'Dim encryptedOutputFile As String = Path.Combine(Directory.GetCurrentDirectory(), "Tes\" + idData + ".pgp")
'C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\Data\
Dim encryptedOutputFileTes As New FileInfo(encryptedOutputFile)
cmd = New MySqlCommand("INSERT INTO `tes`(`tesid`) VALUES ('" + idKey + "')", sql)
sql.Open()
cmd.ExecuteNonQuery()
sql.Close()
pgp.SignAndEncryptFile(FileData, FilePathKey, password, FilePathPublicKey, encryptedOutputFile, asciiArmor, withIntegrityCheck)
'pgp.SignAndEncryptFile(FileData, FilePathKey, password, FilePathPublicKey, encryptedOutputFile, asciiArmor)
'pgp.EncryptFilePBE(FileData, FilePathKey, password, encryptedOutputFile, asciiArmor, withIntegrityCheck)
Dim FullFile As New FullFile(idData + ".pgp", My.Computer.FileSystem.ReadAllText(encryptedOutputFile))
cmd = New MySqlCommand("INSERT INTO `enkripsi_data`(`data`, `key`) VALUES ('" + idData + "','" + idKey + "')", sql)
sql.Open()
cmd.ExecuteNonQuery()
sql.Close()
Dim serializer As New JavaScriptSerializer
serializer.MaxJsonLength = Int32.MaxValue
Dim fullFileJSON = serializer.Serialize(FullFile)
Return fullFileJSON
Else
'File Tidak ada
Return "0"
End If
'Dim FilePath = HttpContext.Current.Server.MapPath("~/" + idKey + ".asc")
End Function
Public Function GetValue(ByVal FileData As String, ByVal password As String) As String
Dim sql As New MySqlConnection()
Dim adapter As New MySqlDataAdapter
Dim FileName As String
FileName = Path.GetFileNameWithoutExtension(FileData)
Dim pgp As New PGPLib()
sql.ConnectionString = "server=localhost;userid=root;database=test"
Dim dt As New DataTable()
Dim cmd As New MySqlCommand("SELECT `key` FROM `enkripsi_data` WHERE `data`='" + FileName + "'", sql)
sql.Open()
adapter = New MySqlDataAdapter(cmd)
adapter.Fill(dt)
sql.Close()
Dim KeyName As String
KeyName = dt.Rows(0)(0).ToString
Dim FilePathKey As String
FilePathKey = Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\", "Coba\" + KeyName + ".key")
Dim decryptedOutputFile As String = Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\", "Coba\Decrypted" + DateTime.Now.ToString(" dd-MM-yyyy HH.mm.ss") + ".bat")
Dim query As String = "Select public_key from public_key LIMIT 1"
Dim ds As New DataSet
cmd = New MySqlCommand(query, sql)
sql.Open()
adapter = New MySqlDataAdapter(cmd)
adapter.Fill(ds)
sql.Close()
Dim FilePathPublicKey As New String(Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\PublicKey\", ds.Tables(0).Rows(0).Item(0).ToString + ".key"))
If File.Exists(FileData) Then
Dim originalFileName As SignatureCheckResult
Try
'pgp.DecryptAndVerifyFile(FileData, FilePathKey, password, FilePathPublicKey, decryptedOutputFile)
'originalFileName = pgp.DecryptFile(FileData, FilePathKey, password, decryptedOutputFile)
originalFileName = pgp.DecryptAndVerifyFile(FileData, FilePathKey, password, FilePathPublicKey, decryptedOutputFile)
'==================================================
Dim fullFile As New FullFile(originalFileName, My.Computer.FileSystem.ReadAllText(decryptedOutputFile))
Dim serializer As New JavaScriptSerializer
serializer.MaxJsonLength = Int32.MaxValue
Dim fullFileJSON = serializer.Serialize(fullFile)
Return fullFileJSON
Catch e As PGPException
If TypeOf e Is NonPGPDataException Then
Return "The input file is not an OpenPGP archive or is corrupted"
ElseIf TypeOf e Is WrongPublicKeyException Then
Return "The supplied public key is not an OpenPGP public key or is corrupted"
ElseIf TypeOf e Is WrongPrivateKeyException Then
' The message cannot be decrypted with this private key
' or the supplied private key is not an OpenPGP private key or is corrupted
Return e.Message
ElseIf TypeOf e Is WrongPasswordException Then
Return "The password for the private key is incorrect"
ElseIf TypeOf e Is FileIsPBEEncryptedException Then
Return "The input file is password encrypted."
Return "You have to use DecryptAndVeifyFilePBE or DecryptAndVerifyStreamPBE"
ElseIf TypeOf e Is IntegrityCheckException Then
Return "The encrypted data is corrupted"
Else
Return e.Message
End If
End Try
Else
'File gak ada
Return "0"
End If
End Function
Here is the problem:
PGPLib.SignAndEncryptFile(dataFIle, signingPrivateKey, signingPrivateKeyPassword, encryptingPublicKey, desitinationFile)
PGPLib.DecryptAndVerifyFile(dataFIle, decryptingPrivateKey, decryptingPrivateKeyPassword, signatureVerifyingPublicKey, desitinationFile)
You use in both cases the same publicKey and the same private key - but PGP cryptography (and the library which implements it) expects when Decrypting to use the private key corresponding to the encryption key used in SignAndEncrypt,
and the verification key to be the corresponding public key of the private key used in SignAndEncrypt.
In essence here is what you shall do:
Dim FilePathPublicKey As New String(Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\PublicKey\", ds.Tables(0).Rows(0).Item(0).ToString + ".key"))
-> FilePathPublicKey must be the signature verifying public key from
ks.GenerateElgamalKeyPair(keySize, email, password)
...
FilePathKey = Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\", "Coba\" + KeyName + ".key")
-> FilePathKey mys be the private key corresponding to the key used for encrypting (the private key of FilePathPublicKey = Path.Combine("C:\Users\user\Desktop\Kuliah\Semester 8\Project\Tes\TES\WindowsApp1\bin\Debug\PublicKey\", dt.Tables(0).Rows(0).Item(0).ToString + ".key")
originalFileName = pgp.DecryptAndVerifyFile(FileData, FilePathKey, password, FilePathPublicKey, decryptedOutputFile)

username and password verification vb.net

My program below checks if the userName and the password is in the database( written in visual basic and uses Access database). The program works however, when I type in the userName or password in a different case it still works. For example, if my database has the userName as "john" and the password as "johnspassword", my program accepts the username as "JOHN" and password as "JOHNSPASSWORD".
how do i resolve this problem?
Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblUsers WHERE UserID = '" & txtUserName_Field.Text & "' AND userPassword = '" & txtUserPassword_Field.Text & "' ", con)
con.Open()
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
'If the record can be queried, it means passing verification, then open another form.
Dim empty =
Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
MessageBox.Show(String.Format("Please fill in all the fields required"))
Else
If (sdr.Read() = True) Then
MessageBox.Show("The is valid!")
Form4.Show()
Me.Hide()
Else
MessageBox.Show("Invalid name or password!")
End If
End If
con.Close()
End Sub
If you use a hash of the password instead then you solve two problems you have:
You should not store passwords as plain text
A hash will make the password case-sensitive
The Rfc2898DeriveBytes Class is suitable for creating the hash; you'll need a randomly-generated salt stored in the database for each user too.
There are many sites, e.g., Salted Password Hashing - Doing it Right, with explanations of why salting and hashing are desirable.
You will still have to decide if you need the username to be case-sensitive.
EDIT
It appears that Access doesn't have an efficient (i.e. sargable) way to do a case-sensitive comparison, so you can simply get the username from the database and check it in your program, something like this:
Option Infer On
Option Strict On
Imports System.Data.OleDb
Imports System.Security.Cryptography
Public Class SomeClass
'TODO: decide on the sizes for the salt and hash
'TODO: create binary fields in the database of appropriate sizes
'TODO: consider storing the number of iterations in the database
Const SALTLENGTH As Integer = 8
Const HASHLENGTH As Integer = 16
Const PBKDF2ITERATIONS As Integer = 20000
Friend Function PBKDF2Hash(password As String, salt As Byte(), iterations As Integer, hashSize As Integer) As Byte()
Dim hasher As New Rfc2898DeriveBytes(password, salt, iterations)
Return hasher.GetBytes(hashSize)
End Function
Function IsLoginValid(username As String, password As String) As Boolean
Dim salt(SALTLENGTH - 1) As Byte
Dim hashedPassword(HASHLENGTH - 1) As Byte
Dim usernameIsValid = False
Dim csb As New OleDbConnectionStringBuilder With {
.Provider = "Microsoft.jet.oledb.4.0",
.DataSource = "C:\Users\jacob\Desktop\MS Office\project.mdb"
}
Using conn As New OleDbConnection(csb.ConnectionString)
'TODO: use the actual column names
Using cmd As New OleDbCommand("SELECT UserID, salt, password FROM tblUsers WHERE UserID = ?", conn)
'TODO: use type of column as specified in the database
cmd.Parameters.Add(New OleDbParameter With {.OleDbType = OleDbType.VarWChar, .Value = username})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
If String.Compare(rdr.GetString(0), username, StringComparison.Ordinal) = 0 Then
rdr.GetBytes(1, 0, salt, 0, SALTLENGTH)
rdr.GetBytes(2, 0, hashedPassword, 0, HASHLENGTH)
usernameIsValid = True
End If
End If
conn.Close()
End Using
End Using
Dim expectedHash = PBKDF2Hash(password, salt, PBKDF2ITERATIONS, HASHLENGTH)
If usernameIsValid AndAlso hashedPassword.SequenceEqual(expectedHash) Then
Return True
End If
Return False
End Function
Private Sub bnLogin_Click(sender As Object, e As EventArgs) Handles bnLogin.Click
Dim username = txtUserName_Field.Text
Dim password = txtUserPassword_Field.Text
If username.Length = 0 OrElse password.Length = 0 Then
MessageBox.Show("Please fill in all the fields required.")
Exit Sub
End If
If IsLoginValid(username, password) Then
' user has supplied valid credentials
Else
MessageBox.Show("Invalid username or password.")
End If
End Sub
End Class
Of course, you still have to create the code to put the appropriate data in the database when the user is registered.

Password hashing - Compare 2 strings

I've just added in a function to hash and salt passwords which are stored in an Access database "Memo" field.
The hashing/salting works fine, but I can't find anything on the internet which tells me how to then decrypt them.
I did see somewhere that says you can't, but instead have to get the password from the database, then hash the entered password (for a log on screen) and compare the 2 strings. I've tried this, but the 2 strings are then different, so I cannot log in.
The algorithms for creating the hash/salt are
Public Shared Function createRandomSalt() As String
Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!£$%^&*()-_=+{}][#'~#:;?/>.<,\|"
Dim salt As String = ""
Dim rnd As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 50
Dim x As Integer = rnd.Next(0, mix.Length - 1)
salt &= (mix.Substring(x, 1))
Next
Return salt
End Function
Public Shared Function Hash512(ByVal password As String, ByVal salt As String)
Dim convertedToBytes As Byte() = Encoding.UTF8.GetBytes(password & salt)
Dim hashType As HashAlgorithm = New SHA512Managed()
Dim hashBytes As Byte() = hashType.ComputeHash(convertedToBytes)
Dim hashedResult As String = Convert.ToBase64String(hashBytes)
Return hashedResult
End Function
Then, when logging in, I'm trying the following
sql = "SELECT * FROM [Users] WHERE [User_ID] = ?"
Dim sCmd As New OleDb.OleDbCommand(sql, mainDBconnection)
sCmd.Parameters.Add("#ID", OleDb.OleDbType.VarChar).Value = txtUser.Text
mainDBadapter = New OleDb.OleDbDataAdapter(sCmd)
mainDBset = New DataSet
mainDBadapter.Fill(mainDBset)
For Each userRow In mainDBset.Tables(0).Rows
Dim password As String = ""
password = mainDBset.Tables(0).Rows(0).Item("Password")
Dim checkPassword As String = (frmSystemSettings.Hash512(password, frmSystemSettings.createRandomSalt))
If userRow.Item("User_ID") = txtUser.Text And password = checkPassword Then
Am I doing something wrong? How can I compare the entered password to the encrypted password in the database?
The problem is you are using a random salt when hashing the entered password. Since that is different from the random salt you used when storing the hash to the DB you get different hashes.
You have to do the following:
Before storing the password to the DB create a random salt, hash the password with it and store the salt together with the password in the database
When a user enters his password retrieve that user's salt from the database, use it to hash the entered password and compare the result to the hash from the database.
Oh, and you seem to never use the password the user entered. In your code you retrieve the hash from the DB into password, hash that hash again into checkpassword and compare those. Of course you have to hash the entered password.

AD not returning the groups which authenticated user belong to

I'm able to authenticate given user - Domain, UserName and Password with LDAP but not able to retrive his groups which he associated with :(
Here the code i'm using
Public Function ValidateActiveDirectoryLogin(ByVal domainName As String, ByVal userName As String, ByVal userPassword As String) As Boolean
Dim isValidated As Boolean = False
Try
Dim ldapPath As String = "LDAP://" & domainName
Dim dirEntry As New DirectoryEntry(ldapPath, userName, userPassword, AuthenticationTypes.Secure)
Dim dirSearcher As New DirectorySearcher(dirEntry)
dirSearcher.Filter = "(SAMAccountName=" & userName & ")"
dirSearcher.PropertiesToLoad.Add("memberOf")
Dim result As SearchResult = dirSearcher.FindOne()
If Not result Is Nothing Then
For Each x As DictionaryEntry In result.Properties
x.Key.ToString()
'DirectCast(x, System.Collections.DictionaryEntry).Key()
Next
Dim groupCount As Integer = result.Properties("memberOf").Count
Dim isInGroup As Boolean = False
For index As Integer = 0 To groupCount - 1
Dim groupDN As String = result.Properties("memberOf").Item(index).ToString
Dim equalsIndex As Integer = groupDN.IndexOf("=")
Dim commaIndex As Integer = groupDN.IndexOf(",")
Dim group As String = groupDN.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1).ToLower
If group.Equals(groupName.ToLower) Then
isInGroup = True
Exit For
End If
Next index
isValidated = isInGroup
End If
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
Return isValidated
End Function
Please help...
Venky
Here is the way I will use, sorry it's code I translate from C# to VB.Net
` Connection to Active Directory
Dim deBase As DirectoryEntry = New DirectoryEntry("LDAP://192.168.183.100:389/dc=dom,dc=fr", "jpb", "pwd")
` Directory Search for the group your are interested in
Dim dsLookForGrp As DirectorySearcher = New DirectorySearcher(deBase)
dsLookForGrp.Filter = String.Format("(cn={0})", "yourgroup")
dsLookForGrp.SearchScope = SearchScope.Subtree
dsLookForGrp.PropertiesToLoad.Add("distinguishedName")
Dim srcGrp As SearchResult = dsLookForGrp.FindOne
If (Not (srcGrp) Is Nothing) Then
Dim dsLookForUsers As DirectorySearcher = New DirectorySearcher(deBase)
dsLookForUsers.Filter = String.Format("(&(objectCategory=person)(memberOf={0}))", srcGrp.Properties("distinguishedName")(0))
dsLookForUsers.SearchScope = SearchScope.Subtree
dsLookForUsers.PropertiesToLoad.Add("objectSid")
dsLookForUsers.PropertiesToLoad.Add("userPrincipalName ")
dsLookForUsers.PropertiesToLoad.Add("sAMAccountName")
Dim srcLstUsers As SearchResultCollection = dsLookForUsers.FindAll
For Each sruser As SearchResult In srcLstUsers
Console.WriteLine("{0}", sruser.Path)
` Here Test if you username is insode
Console.WriteLine(""& vbTab&"{0} : {1} ", "sAMAccountName", sruser.Properties("sAMAccountName")(0))
Next
End If
Be careful the primary group is given by the primaryGroupID and it's not a DN but an ID which is the lasr part of the group SID.
Last thing, But you can also do it using Managing Directory Security Principals in the .NET Framework 3.5. Here is a sample in C#
/* Retreiving a principal context
*/
Console.WriteLine("Retreiving a principal context");
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "PWD");
/* Look for all the groups a user belongs to
*/
UserPrincipal aUser = UserPrincipal.FindByIdentity(domainContext, "user1");
PrincipalSearchResult<Principal> a = aUser.GetAuthorizationGroups();
foreach (GroupPrincipal gTmp in a)
{
Console.WriteLine(gTmp.Name);
}

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