Imports System.Configuration
Imports System.Security.Cryptography
Imports System.Text
Imports Strata.Configuration.Client.Models.Jazz

Namespace Encryptors

    Public Class UserGUIDEncryptionMethod
        Implements IPasswordEncryptionMethod

#Region " Declarations "

        Private Const NUMBER_ITERATIONS As Integer = 100000

#End Region

#Region " Methods "

        Public Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode
            Dim salt As String = aUserGUID.ToString & ConfigurationManager.AppSettings(NameOf(StrataJazzOptions.UserGuidEncryptionKey))

            Dim result As String = GetHashedValue(aNewPassword, salt)
            For i As Integer = 1 To NUMBER_ITERATIONS
                result = GetHashedValue(result)
            Next

            Return result
        End Function

        Private Shared Function GetHashedValue(ByVal aValue As String) As String

            'Create an instance of the sha encrypter
            Using hasher As HashAlgorithm = SHA256.Create()
                Return Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(aValue)))
            End Using

        End Function

        Private Shared Function GetHashedValue(ByVal aValue As String, ByVal aSalt As String) As String
            Return GetHashedValue(aValue & aSalt)
        End Function

#End Region

    End Class

End Namespace
