Skip to content

Commit

Permalink
Contraseñas Usuarios
Browse files Browse the repository at this point in the history
En lugar de guardar las contraseñas de usuario en texto plano se guarda el hash sha512 de la misma y el salt utilizado el cual es distinto y aleatorio para cada usuario.
  • Loading branch information
mauryparra committed Dec 6, 2017
1 parent 12417e1 commit 52cdeaf
Show file tree
Hide file tree
Showing 7 changed files with 171 additions and 28 deletions.
134 changes: 128 additions & 6 deletions SireCu/Clases/Usuario.vb
Original file line number Diff line number Diff line change
@@ -1,17 +1,139 @@
Module Usuario

Public Function verificarUsuario(ByVal user As String, ByVal pass As String)
Public Class SampleIPrincipal
Implements System.Security.Principal.IPrincipal

Dim sql As String = "SELECT * FROM Usuarios WHERE usuario = '" & user & "'"
Private identityValue As SampleIIdentity

Public ReadOnly Property Identity() As System.Security.Principal.IIdentity Implements System.Security.Principal.IPrincipal.Identity
Get
Return identityValue
End Get
End Property

Public Function IsInRole(ByVal role As String) As Boolean Implements System.Security.Principal.IPrincipal.IsInRole
Return role = identityValue.Role.ToString
End Function

Public Sub New(ByVal name As String, ByVal password As String)
identityValue = New SampleIIdentity(name, password)
End Sub

End Class

Public Class SampleIIdentity
Implements System.Security.Principal.IIdentity

Private nameValue As String
Private authenticatedValue As Boolean
Private roleValue As ApplicationServices.BuiltInRole

Public ReadOnly Property AuthenticationType As String Implements System.Security.Principal.IIdentity.AuthenticationType
Get
Return "SqlCEDatabase"
End Get
End Property

Public ReadOnly Property IsAuthenticated As Boolean Implements System.Security.Principal.IIdentity.IsAuthenticated
Get
Return authenticatedValue
End Get
End Property

Public ReadOnly Property Name As String Implements System.Security.Principal.IIdentity.Name
Get
Return nameValue
End Get
End Property

Public ReadOnly Property Role() As ApplicationServices.BuiltInRole
Get
Return roleValue
End Get
End Property

Public Sub New(ByVal name As String, ByVal password As String)
' Contraseña es Case Sensitive, el Usuario no lo es
If IsValidNameAndPassword(name, password) Then
nameValue = name
authenticatedValue = True
Else
nameValue = ""
authenticatedValue = False
End If

End Sub

Private Function IsValidNameAndPassword(ByVal username As String, ByVal password As String) As Boolean

' Look up the stored hashed password and salt for the username.
Dim storedHashedPW As String = GetHashedPassword(username)
Dim salt As String = GetSalt(username)

'Create the salted hash.
Dim rawSalted As String = salt & Trim(password)
Dim saltedPwBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(rawSalted)
Dim sha512 As New System.Security.Cryptography.SHA512CryptoServiceProvider
Dim hashedPwBytes() As Byte = sha512.ComputeHash(saltedPwBytes)
Dim hashedPw As String = Convert.ToBase64String(hashedPwBytes)

' Compare the hashed password with the stored password.
Return hashedPw = storedHashedPW

End Function


End Class

Friend Function GetHashedPassword(ByVal username As String) As String
' Code that gets the user's hashed password

Dim sql As String = "SELECT contraseña FROM Usuarios WHERE usuario = '" & username & "'"
Dim dt As DataTable = consultarReader(sql)

If dt.Rows.Count = 0 Then
Return False
ElseIf dt.Rows(0).Item("contraseña") = pass Then
Return True
Else Return False
Return ""
Else
Return dt.Rows(0).Item("contraseña")
End If
End Function

Friend Function GetSalt(ByVal username As String) As String
' Code that gets the user's salt

Dim sql As String = "SELECT salt FROM Usuarios WHERE usuario = '" & username & "'"
Dim dt As DataTable = consultarReader(sql)

If dt.Rows.Count = 0 Then
Return ""
Else
Return dt.Rows(0).Item("salt")
End If
End Function

Public Function CreateRandomSalt() As String
'the following is the string that will hold the salt charachters
Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=][}{<>"
Dim salt As String = ""
Dim rnd As New Random
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To 100 'Length of the salt
Dim x As Integer = rnd.Next(0, mix.Length - 1)
salt &= (mix.Substring(x, 1))
Next
Return salt
End Function

Public Function CreateHashedPassword(ByVal contraseña As String, ByVal salt As String) As String

'Create the hashed password.
Dim rawSalted As String = salt & Trim(contraseña)
Dim saltedPwBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(rawSalted)
Dim sha512 As New System.Security.Cryptography.SHA512CryptoServiceProvider
Dim hashedPwBytes() As Byte = sha512.ComputeHash(saltedPwBytes)
Dim hashedPw As String = Convert.ToBase64String(hashedPwBytes)

Return hashedPw
End Function

Public Function tipoDeUsuario(ByVal user As String)
Expand Down
Binary file modified SireCu/DBSireCu.sdf
Binary file not shown.
18 changes: 9 additions & 9 deletions SireCu/My Project/Application.Designer.vb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions SireCu/My Project/Application.myapp
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-16"?>
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>true</MySubMain>
<MainForm>Principal</MainForm>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<AuthenticationMode>1</AuthenticationMode>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>
23 changes: 18 additions & 5 deletions SireCu/Paneles/ABMUsuarios.vb
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ Public Class ABMUsuarios
End If
Else
Principal.ErrorProvider.SetError(cb_Rol, "")
ControlesConErrores.Remove(cb_Rol)
If ControlesConErrores.Contains(cb_Rol) Then
ControlesConErrores.Remove(cb_Rol)
End If
End If

If ControlesConErrores.Count > 0 Then
Expand All @@ -85,9 +87,16 @@ Public Class ABMUsuarios
If (MsgBox("Quiere Modificar al usuario " & DGVAdmin.CurrentRow.Cells(1).Value & "?",
MsgBoxStyle.OkCancel, "Modificar?") = MsgBoxResult.Ok) Then

Dim contraseña As String = ""
If tb_Contraseña.Text = Usuario.GetHashedPassword(DGVAdmin.CurrentRow.Cells(1).Value) Then
contraseña = tb_Contraseña.Text
Else
contraseña = Usuario.CreateHashedPassword(tb_Contraseña.Text, Usuario.GetSalt(DGVAdmin.CurrentRow.Cells(1).Value))
End If

Principal.query = "UPDATE [Usuarios] SET " &
"usuario = '" & tb_Usuario.Text &
"' ,contraseña = '" & tb_Contraseña.Text &
"' ,contraseña = '" & contraseña &
"' ,rol = '" & cb_Rol.Text &
"' WHERE id= '" & DGVAdmin.CurrentRow.Cells(0).Value & "'"
consultarNQ(Principal.query, Principal.command)
Expand All @@ -106,10 +115,13 @@ Public Class ABMUsuarios

If (MsgBox("Guardar nuevo usuario?", MsgBoxStyle.OkCancel, "Guardar?") = MsgBoxResult.Ok) Then

Principal.query = "INSERT INTO [Usuarios] (usuario,contraseña, rol)
Dim salt As String = Usuario.CreateRandomSalt()
Dim contraseña As String = Usuario.CreateHashedPassword(tb_Contraseña.Text, salt)

Principal.query = "INSERT INTO [Usuarios] (usuario, contraseña, rol, salt)
VALUES ('" &
tb_Usuario.Text & "', '" & tb_Contraseña.Text &
"', '" & cb_Rol.Text & "')"
tb_Usuario.Text & "', '" & contraseña &
"', '" & cb_Rol.Text & "', '" & salt & "')"
consultarNQ(Principal.query, Principal.command)

MsgBox("Guardado Correctamente!", MsgBoxStyle.Information, "Guardado")
Expand Down Expand Up @@ -224,6 +236,7 @@ Public Class ABMUsuarios
DGVAdmin.Columns.Item("usuario").HeaderText = "Usuario"
DGVAdmin.Columns.Item("contraseña").HeaderText = "Contraseña"
DGVAdmin.Columns.Item("rol").HeaderText = "Rol"
DGVAdmin.Columns.Item("salt").Visible = False

End Sub

Expand Down
17 changes: 11 additions & 6 deletions SireCu/Paneles/Login.vb
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,25 @@ Public Class Login

Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click

'Validaciones
If verificarUsuario(tb_Usuario.Text, tb_Contraseña.Text) Then
Dim samplePrincipal As New Usuario.SampleIPrincipal(Me.tb_Usuario.Text, Me.tb_Contraseña.Text)
Me.tb_Contraseña.Text = ""
If (Not samplePrincipal.Identity.IsAuthenticated) Then
' The user is still not validated.
Principal.ErrorProvider.SetError(tb_Contraseña, "Usuario y/o Contraseña Inválido/s")
Else
' Update the current principal.
My.User.CurrentPrincipal = samplePrincipal

Principal.bttn_Login.Text = "Desloguear"
Principal.stat_Label.Text = "Logueado como: " & tb_Usuario.Text
Principal.userLogueado = tb_Usuario.Text
Principal.stat_Label.Text = "Logueado como: " & My.User.Name
Principal.userLogueado = My.User.Name

ActualizarSaldo()
permisosUsuarios(tb_Usuario.Text)

' Limpiamos todas las pantallas
Principal.SplitContainerPrincipal.Panel2.Controls.Clear()
Principal.AdminPantallas("Home")
Else
Principal.ErrorProvider.SetError(tb_Contraseña, "Usuario y/o Contraseña Inválido/s")
End If

End Sub
Expand Down
3 changes: 3 additions & 0 deletions SireCu/Principal.vb
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ Public Class Principal
End Sub
Private Sub desloguear()

' Se borra la identidad auntenticada en la aplicación
My.User.CurrentPrincipal = Nothing

' Limpiamos todas las pantallas
SplitContainerPrincipal.Panel2.Controls.Clear()

Expand Down

0 comments on commit 52cdeaf

Please sign in to comment.