'  
'   Rebex Sample Code License
' 
'   Copyright 2025, 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

    Function Request(ByVal socket As TlsSocket, ByVal issuers() As DistinguishedName) As CertificateChain Implements ICertificateRequestHandler.Request
        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

        Console.WriteLine("Select certificate:")
    Dim i As Integer
        For i = 0 To certs.Length
            If i = 0 Then
                Console.WriteLine(String.Format("{0}. [Nothing, skip this step]", i))
            Else
                Console.WriteLine(String.Format("{0}. {1}", i, certs(i - 1).GetSubjectName()))
            End If
        Next i

        While True
            Console.Write(String.Format("Select certificate [0 - {0}]: ", certs.Length))

            Dim certIndex As Integer = -1
            Dim err As Boolean = False

            Try
                certIndex = Integer.Parse(Console.ReadLine())
            Catch
                Console.WriteLine("ERROR: Wrong input!")
                err = True
            End Try

            If certIndex > 0 AndAlso certIndex <= certs.Length Then
                Return CertificateChain.BuildFrom(certs(certIndex))
            Else
                If certIndex = 0 Then
                    Exit While
                End If

                If Not err Then
                    Console.WriteLine(String.Format("ERROR: You must enter number between 0 and {0}.", certs.Length))
                End If
            End If
        End While

        Return Nothing
    End Function

End Class

