'  
'   Rebex Sample Code License
' 
'   Copyright 2026, REBEX CR s.r.o.
'   All rights reserved.
'   https://www.rebex.net/
' 
'   Permission to use, copy, modify, and/or distribute this software for any
'   purpose with or without fee is hereby granted.
' 
'   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
'   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
'   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
'   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
'   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
'   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
'   OTHER DEALINGS IN THE SOFTWARE.
' 

Imports Rebex.Net
Imports Rebex.Security.Certificates

Public Class RequestHandler
    Implements ICertificateRequestHandler

    Private Shared ReadOnly _chosenCertificates As Hashtable = New Hashtable

    Function Request(ByVal socket As TlsSocket, ByVal issuers() As DistinguishedName) As CertificateChain Implements ICertificateRequestHandler.Request

        Dim serverCertificateFingerprint As String = BitConverter.ToString( _
            socket.ServerCertificate.LeafCertificate.GetCertHash())

        If _chosenCertificates.Contains(serverCertificateFingerprint) Then
            Return _chosenCertificates(serverCertificateFingerprint)
        End If

        Dim my As CertificateStore = New CertificateStore("MY")
        Dim certs As Certificate()

        If issuers.Length > 0 Then
            certs = my.FindCertificates(issuers, CertificateFindOptions.IsTimeValid Or CertificateFindOptions.HasPrivateKey Or CertificateFindOptions.ClientAuthentication)
        Else
            certs = my.FindCertificates(CertificateFindOptions.IsTimeValid Or CertificateFindOptions.HasPrivateKey Or CertificateFindOptions.ClientAuthentication)
        End If

        If certs.Length = 0 Then
            Return Nothing
        End If

        Dim rhForm As RequestHandlerForm = New RequestHandlerForm
        rhForm.LoadData(certs)

        If rhForm.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Dim chain As CertificateChain = Nothing

            If Not rhForm.Certificate Is Nothing Then
                chain = CertificateChain.BuildFrom(rhForm.Certificate)
            End If

            ' save chosen certificate for the server in static HashTable
            _chosenCertificates.Add(serverCertificateFingerprint, chain)

            Return chain
        End If

        Return Nothing
    End Function

End Class

