Imports System.IO
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        FirmaPDFPFX("prueba", "prueba", "prueba", "c:\tmp\pruebafirmada.pdf", True, True)
    End Sub

    Public Shared Sub FirmaPDFPFX(Razon As String, Contacto As String, Localizacion As String, FicheroPdfDef As String, EliminaFirmasAnteriores As Boolean, Optional EliminaFicheroDestino As Boolean = False)
        Dim p As String = "prueba1234."
        Try
            Dim bpfx = IO.File.ReadAllBytes("C:\tmp\mmm.pfx")
            Dim bpdf = IO.File.ReadAllBytes("c:\tmp\E_2026-00322_sellado.pdf")
            Dim pk As New X509Certificate2(bpfx, p, X509KeyStorageFlags.Exportable)
            CambiaKeyContainerName(pk)
            If pk.NotAfter < Now Then Throw New Exception("El certificado está caducado")
            '     If Not pk.Subject.Contains("CN=" & DocumentoIdentidad) Then Throw New Exception("El certificado no pertenece al validador")
            Dim ms As New MemoryStream
            'tsUtilsPDF.pdf.FirmaPDF(pk, "", PdfStream, ms, Razon, Contacto, Localizacion, RutaTmp, EliminaFirmasAnteriores)            
            TSpdfUtils.Firmas.FirmaPDF(bpfx, p, "", New MemoryStream(bpdf), ms, Razon, Contacto, Localizacion, EliminaFirmasAnteriores)
            If EliminaFicheroDestino AndAlso IO.File.Exists(FicheroPdfDef) Then IO.File.Delete(FicheroPdfDef)
            IO.File.WriteAllBytes("c:\tmp\pruebafirmada.pdf", ms.ToArray)
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub
    Public Shared Sub CambiaKeyContainerName(ByRef Certificado As System.Security.Cryptography.X509Certificates.X509Certificate2)
        Dim rsa As RSACryptoServiceProvider = CType(Certificado.PrivateKey, RSACryptoServiceProvider)
        Dim csparams As New CspParameters
        csparams.KeyContainerName = "TECNOSIS-" & Guid.NewGuid.ToString
        Dim rsa2 As New RSACryptoServiceProvider(csparams)
        rsa2.ImportParameters(rsa.ExportParameters(True))
        Certificado.PrivateKey = rsa2
    End Sub
End Class
