Imports System.IO
Imports Org.BouncyCastle.Pkcs
Imports TSpdf.Bouncycastle.Cert
Imports TSpdf.Bouncycastle.Crypto
Imports TSpdf.Commons.Bouncycastle.Cert
Imports TSpdf.Commons.Bouncycastle.Crypto
Imports TSpdf.Kernel.Pdf
Imports TSpdf.Signatures

Public Class FirmaTiempo

    Public Shared Sub SignPdfWithTimestamp(src As String, dest As String, keystorePath As Stream, keystorePassword As String, tsaUrl As String)
        Dim reader As New PdfReader(src)
        Dim output As New FileStream(dest, FileMode.Create)
        Dim signer As New PdfSigner(reader, output, New StampingProperties())


        ' Se coge los datos del certificado
        Dim cpassword = keystorePassword.ToCharArray

        Dim [alias] As String = Nothing
        Dim pk12 As Pkcs12Store = New Pkcs12Store(keystorePath, cpassword)

        For Each a In pk12.Aliases
            [alias] = (CType(a, String))

            If pk12.IsKeyEntry([alias]) Then
                Exit For
            End If
        Next

        Dim pk As IPrivateKey = New PrivateKeyBC(pk12.GetKey([alias]).Key)
        Dim pks = New PrivateKeySignature(pk, DigestAlgorithms.SHA256)


        Dim ce As X509CertificateEntry() = pk12.GetCertificateChain([alias])
        Dim chain = New IX509Certificate(ce.Length - 1) {}

        For k As Integer = 0 To ce.Length - 1
            chain(k) = New X509CertificateBC(ce(k).Certificate)
        Next

        Dim externalSignature As IExternalSignature = New PrivateKeySignature(pk, "SHA-256")

        ' Aqui va la URL del servicio de sellado de tiempo
        Dim tsaClient As ITSAClient = New TSAClientBouncyCastle(tsaUrl)

        ' Se hace la firma con el sellado de tiempo que se le pasa por parámetro
        signer.SignDetached(externalSignature, chain, Nothing, Nothing, tsaClient, 0, PdfSigner.CryptoStandard.CADES)
    End Sub

End Class
