1

Como se puede firmar un documento XML con un certificado no exportable?

Hasta ahora empleaba el siguiente código en visual basic, pero solo es válido para certificados exportables debido a la linea en la que carga la clave privada, pero me encuentro en la situación de que debo firmar con certificados no exportables.

Se debe poder, ya que por ejemplo, con estos certificados he podido firmar documentos word, excel o pdf usando sus respectivas aplicaciones.

Este es el código que tengo actualmente:

Public Function GetCertificado() As X509Certificate2
    Dim store As X509Store = New X509Store
    store.Open((OpenFlags.ReadOnly Or OpenFlags.OpenExistingOnly))
    Dim collection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
    Dim fcollection As X509Certificate2Collection = CType(collection.Find(X509FindType.FindByTimeValid, DateTime.Now, False), X509Certificate2Collection)
    Dim scollection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificados", "Seleccione un certificado", X509SelectionFlag.SingleSelection)
    If (scollection.Count = 0) Then
        Return Nothing
    End If
    Return scollection(0)
End Function
Public Sub Sign(cert As X509Certificate2, route as String)
    Dim doc As XmlDocument = New XmlDocument()
    doc.LoadXml(File.ReadAllText(route))

    Dim signedxml As SignedXml = New SignedXml(doc)
    Dim reference As Reference = New Reference()
    reference.Uri = ""
    Dim env As XmlDsigEnvelopedSignatureTransform = New XmlDsigEnvelopedSignatureTransform()
    reference.AddTransform(env)
    signedxml.AddReference(reference)

    Dim KeyInfo As KeyInfo = New KeyInfo()
    KeyInfo.AddClause(New KeyInfoX509Data(cert))
    signedxml.KeyInfo = KeyInfo
    signedxml.SigningKeyName = cert.Subject

    signedxml.SigningKey = cert.PrivateKey '<--- origen de error'
    signedxml.ComputeSignature()
    Dim xmlsig As XmlElement = signedxml.GetXml()
    doc.DocumentElement.AppendChild(doc.ImportNode(xmlsig, True))
End Sub

Si no es posible hacerlo en visual basic, valdría cualquier solución usando otros lenguajes como java, javascript, C#.

1
  • mil gracias! Me ha venido de perlas tu código. el 29 jun. 2022 a las 14:52

1 respuesta 1

1

Solucionado.

Cambiando: signedxml.SigningKey = cert.PrivateKey

Por: signedxml.SigningKey = cert.GetRSAPrivateKey

No podia usarlo previamente porque requiere .Net Framework 4.6 o mayor, previamente trabajaba en .Net Framework 4.5.2, asi que cambiando la versión se ha solucionado.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.