EldoS | Feel safer!

Software components for data protection, secure storage and transfer

Trying to Signing with tElSignedCMSMessage validating with signedcms

Also by EldoS: CallbackRegistry
A component to monitor and control Windows registry access and create virtual registry keys.
#36614
Posted: 05/02/2016 08:38:16
by Javier Aranda (Basic support level)
Joined: 05/02/2016
Posts: 8

I trying to signing with tElSignedCMSMessage DC and testing validation with System.Security.Cryptography.Pkcs.SignedCms, i get error System.Security.Cryptography.CryptographicException 'ASN1 bad tag value met' on call to signed.Decode
┬┐what i am doing wrong? thanks.

Signing:
Code
Private Sub PreSigner()

            Dim txt As System.Web.UI.WebControls.TextBox = FindControl(ControlAFirmar)

            If Not IsNothing(txt) Then
                SBUtils.Unit.SetLicenseKey("xxx")
                Dim tElDCAsyncState As TElDCAsyncState = Nothing

                Dim tElSignedCMSMessage As TElSignedCMSMessage = New TElSignedCMSMessage()
                Dim bytes As Byte() = System.Text.Encoding.Unicode.GetBytes(txt.Text)
                tElSignedCMSMessage.CreateNew(bytes, 0, bytes.Length)
                Dim index As Integer = tElSignedCMSMessage.AddSignature()
                tElSignedCMSMessage.GetSignature(index).DigestAlgorithm = SBConstants.Unit.SB_ALGORITHM_DGST_SHA1
                tElSignedCMSMessage.GetSignature(index).SigningOptions = (tElSignedCMSMessage.GetSignature(index).SigningOptions And -9)
                tElSignedCMSMessage.GetSignature(index).SigningTime = DateTime.Now
                tElSignedCMSMessage.GetSignature(index).PublicKeyAlgorithm = SBPGPConstants.Unit.SB_PGP_ALGORITHM_PK_RSA_SIGN
                tElSignedCMSMessage.GetSignature(index).InitiateAsyncSign(tElDCAsyncState)


                Dim tElDCBaseMessage As TElDCBaseMessage = tElDCAsyncState.FindMessageByType(TElDCOperationRequestMessage.MetaClass.Instance)
                Dim flag As Boolean = tElDCBaseMessage IsNot Nothing
                If flag Then
                    CType(tElDCBaseMessage, TElDCOperationRequestMessage).IncludeKeysInResponse = True
                End If
                Me.output = New MemoryStream()
                Dim encoding As TElDCXMLEncoding = New TElDCXMLEncoding()

                tElDCAsyncState.SaveToStream(Me.output, encoding)
                tElSignedCMSMessage.Close()
                tElDCAsyncState.Dispose()
            Else
                Throw New Exception("Error '" & ControlAFirmar & "'")
            End If

        End Sub


Validation:
Code
    Public Function VerifySignature(signature As String) As Boolean
        Dim input As Byte() = System.Text.Encoding.Unicode.GetBytes(TextBoxAdv1.Text)
        Dim content As New ContentInfo(input)
        Dim signed As New SignedCms(content, True)
        signed.Decode(Convert.FromBase64String(signature))
        signed.CheckSignature(True)
        Dim certificate As X509Certificate2 = signed.Certificates(0)
        'MessageBox.Show("Certificate :" + certificate.Subject + vbLf + "Issuer :" + certificate.Issuer)
    End Function
#36615
Posted: 05/02/2016 08:48:14
by Eugene Mayevski (EldoS Corp.)

Before trying third-party validation, try to validate the product of your signing (i.e. the signed data) with TElMessageVerifier. You can use the sample in SecureBlackbox\Samples\PKIBlackbox\Desktop\PKCS7 directory for quick verification.

The code you've quoted is just the first part of the signing procedure. I assume you also have the second part as well, and not trying to validate the AsyncState as a signed data?


Sincerely yours
Eugene Mayevski
#36617
Posted: 05/02/2016 10:06:45
by Javier Aranda (Basic support level)
Joined: 05/02/2016
Posts: 8

Thanks for your quick answer,

TElMessageVerifier.Verify return code #8198

SB_MESSAGE_ERROR_INVALID_FORMAT 8198 (0x2006) The message passed to Decrypt/Verify routine is not valid PKCS7 message.

here is second part of signing procedure:
Code
   Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
            SBUtils.Unit.SetLicenseKey("xxxx")
            Dim flag As Boolean = MyBase.Request.InputStream.Length > 0L
            If flag Then
                Dim array As Byte() = New Byte(MyBase.Request.InputStream.Length - 1) {}
                MyBase.Request.InputStream.Read(array, 0, array.Length)
                Me.FinishSigning(array)
            End If
            Dim flag2 As Boolean = Me.Session("signature") IsNot Nothing
            If flag2 Then
                Me.labelResult.Text = Me.Session("signature").ToString()
            End If
        End Sub

        Protected Sub FinishSigning(signature As Byte())
            Dim tElDCAsyncState As TElDCAsyncState = New TElDCAsyncState()
            Try
                Dim sessionId As String = ""
                Dim stream As MemoryStream = New MemoryStream(signature)
                tElDCAsyncState.LoadFromStream(stream, SBDCXMLEnc.__Global.DCXMLEncoding())
                Dim tElSignedCMSMessage As TElSignedCMSMessage = New TElSignedCMSMessage()

                Dim path As String = Sonda.Net.Configuracion.BaseWebTempDir.TrimEnd + "\FirmaDigital"
                Dim fileStream As FileStream = File.OpenRead(path + "\" + Me.Request.QueryString("ID") + ".bin")
                tElSignedCMSMessage.Open(fileStream, Nothing, 0L, 0L)
                Dim index As Integer = 0
                Try
                    Dim signature2 As TElCMSSignature = tElSignedCMSMessage.GetSignature(index)
                    signature2.CompleteAsyncSign(tElDCAsyncState)
                    Dim fileSignature As String = path + "\" + Me.Request.QueryString("ID") + ".sig"
                    File.WriteAllBytes(fileSignature, signature2.Content)
                Finally
                    tElSignedCMSMessage.GetSignature(index).Dispose()
                End Try
                fileStream.Close()
            Finally
                tElDCAsyncState.Dispose()
            End Try
        End Sub


here is TElMessageVerifier validation code:
Code
  Private Sub DoVerification(signature As String)
        Dim v As New SBMessages.TElMessageVerifier
        'v.CertStorage = MemoryCertStorage

        Dim Buf() As Byte = Convert.FromBase64String(signature)
        If Buf Is Nothing Then Return

        Dim intSize As Integer
        Dim OutBuf() As Byte
        OutBuf = Nothing

        v.Verify(Buf, OutBuf, intSize)
        ReDim OutBuf(intSize - 1)
        Dim i As Integer = v.Verify(Buf, OutBuf, intSize)
        If i = 0 Then
            'WriteDestination(OutBuf, intSize)
            LogLine("Verifying results:")

            LogLine("Successfully verified!" + ControlChars.CrLf)
            If (v.SignatureType = SBMessages.TSBMessageSignatureType.mstMAC) Then
                LogLine("Signature type: MAC")
            Else
                LogLine("Signature type: PUBLIC KEY")
            End If
            LogLine(ControlChars.CrLf)
            LogLine("Hash Algorithm: ")
            LogLine(GetAlgorithmName(v.HashAlgorithm))
            LogLine(ControlChars.CrLf)
            If (v.SignatureType = SBMessages.TSBMessageSignatureType.mstMAC) Then
                LogLine("MAC Algorithm: ")
                LogLine(GetAlgorithmName(v.MacAlgorithm))
                LogLine(ControlChars.CrLf)
            End If
            LogLine("Certificates contained in message:" + ControlChars.CrLf)
            LogLine(GetCertificatesInfo(v.Certificates))
        Else
            LogLine("Verification failed with error #" + i.ToString)
        End If

    End Sub
#36618
Posted: 05/02/2016 11:16:06
by Javier Aranda (Basic support level)
Joined: 05/02/2016
Posts: 8

Find my mistake, i was validating against signature and not whole message.

Now is validating with your API , but not with signedcms from microsoft.

I also notice than message include all certificates in my store. So i have more questions.

How can i detect wich certificate was used in signature?
How could i remove others certificates from message?
Why signedcms do not validate? it throws The hash value is not correct.

Quote

---=== Validate sbb ===---
Verifying results:
Successfully verified!

Signature type: PUBLIC KEY


Hash Algorithm:
SHA256


Certificates contained in message:

Certificate #1
Issuer: C=, L=, O=, CN=sonda-GARZA3-CA
Subject: C=CL, L=Santiago, O=Sonda, CN=Javier Aranda DS
Private key is not available
Certificate #2
Issuer: C=, L=, O=DO_NOT_TRUST, CN=DO_NOT_TRUST_FiddlerRoot
Subject: C=, L=, O=DO_NOT_TRUST, CN=DO_NOT_TRUST_FiddlerRoot
Private key is not available
Certificate #3
Issuer: C=, L=, O=, CN=Communications Server
Subject: C=, L=, O=, CN=javier.aranda@sonda.com
Private key is not available
Certificate #4
Issuer: C=, L=, O=, CN=sonda-dc04
Subject: C=, L=, O=, CN=Aranda Leiva, Javier
Private key is not available
Certificate #5
Issuer: C=, L=, O=, CN=SONDA_USUARIOS\Javier.Aranda
Subject: C=, L=, O=, CN=SONDA_USUARIOS\Javier.Aranda
Private key is not available
Certificate #6
Issuer: C=si, L=, O=state-institutions, CN=
Subject: C=si, L=, O=state-institutions, CN=Janez Novak
Private key is not available

---=== End Validate sbb ===---
---=== Validate .net ===---
Error: The hash value is not correct.

---=== End Validate .net ===---


Validation code updated
Code
Public Function VerifySignature(signature As String) As Boolean
        LogLine("---=== Validate .net ===---")
        Try
            Dim input As Byte() = System.Text.Encoding.Unicode.GetBytes(TextBoxAdv1.Text)
            Dim content As New ContentInfo(input)
            Dim signed As New SignedCms(content, True)
            signed.Decode(Convert.FromBase64String(signature))
            signed.CheckSignature(True)
            Dim certificate As X509Certificate2 = signed.Certificates(0)
            LogLine("Certificate :" + certificate.Subject + vbLf + "Issuer :" + certificate.Issuer)
        Catch ex As Exception
            LogLine("Error: " + ex.Message)
        End Try
        LogLine("---=== End Validate .net ===---")
    End Function


    Private Sub DoVerification(signature As String)
        LogLine("---=== Validate sbb ===---")
        Try
            Dim v As New SBMessages.TElMessageVerifier
            'v.CertStorage = MemoryCertStorage

            Dim Buf() As Byte = Convert.FromBase64String(signature)
            If Buf Is Nothing Then Return

            Dim intSize As Integer
            Dim OutBuf() As Byte
            OutBuf = Nothing

            v.Verify(Buf, OutBuf, intSize)
            ReDim OutBuf(intSize - 1)
            Dim i As Integer = v.Verify(Buf, OutBuf, intSize)
            If i = 0 Then
                'WriteDestination(OutBuf, intSize)
                LogLine("Verifying results:")

                LogLine("Successfully verified!" + ControlChars.CrLf)
                If (v.SignatureType = SBMessages.TSBMessageSignatureType.mstMAC) Then
                    LogLine("Signature type: MAC")
                Else
                    LogLine("Signature type: PUBLIC KEY")
                End If
                LogLine(ControlChars.CrLf)
                LogLine("Hash Algorithm: ")
                LogLine(GetAlgorithmName(v.HashAlgorithm))
                LogLine(ControlChars.CrLf)
                If (v.SignatureType = SBMessages.TSBMessageSignatureType.mstMAC) Then
                    LogLine("MAC Algorithm: ")
                    LogLine(GetAlgorithmName(v.MacAlgorithm))
                    LogLine(ControlChars.CrLf)
                End If
                LogLine("Certificates contained in message:" + ControlChars.CrLf)
                LogLine(GetCertificatesInfo(v.Certificates))
            Else
                LogLine("Verification failed with error #" + i.ToString)
            End If
        Catch ex As Exception
            LogLine("Error: " + ex.Message)
        End Try
        LogLine("---=== End Validate sbb ===---")
    End Sub
#36626
Posted: 05/03/2016 06:37:13
by Eugene Mayevski (EldoS Corp.)

It is hard to say, what's wrong with your code by seeing only pieces of it, but there's a couple of things that would benefit from correction:

1) the code tElDCBaseMessage As TElDCBaseMessage = tElDCAsyncState.FindMessageByType(TElDCOperationRequestMessage.MetaClass.Instance) doesn't make much sense. TElDCOperationRequestMessage is a direct descendant of TElBaseMessage

2) tElSignedCMSMessage.GetSignature(index).PublicKeyAlgorithm = SBPGPConstants.Unit.SB_PGP_ALGORITHM_PK_RSA_SIGN -- the SB_PGP_ constant should not be used here. SB_ALGORITHM_PK_RSA should be used instead.

Finally, I don't know .NET classes (we work with SecureBlackbox, not with third-party software), but it seems that you are checking the wrong data with .NET. I can't correct your .NET code, though.


Sincerely yours
Eugene Mayevski
#36628
Posted: 05/03/2016 06:59:44
by Javier Aranda (Basic support level)
Joined: 05/02/2016
Posts: 8

Eugene,

Thanks for your patience, i found my error. There is correct code for validating signatures generated with TElSignedCMSMessage with .net classes. It could help to others.

The problem was second parameter on SignedCms constructor.

I will open other thread for my remaining doubts.

Code
    Public Function VerifySignature(signature As String) As Boolean
        LogLine("---=== Validate .net ===---")
        Try
            Dim input As Byte() = System.Text.Encoding.Unicode.GetBytes(TextBoxAdv1.Text)
            Dim content As New ContentInfo(input)
            [B]Dim signed As New SignedCms(content, False)[/B]
            signed.Decode(Convert.FromBase64String(signature))
            signed.CheckSignature(True)
            Dim certificate As X509Certificate2 = signed.Certificates(0)
            LogLine("Certificate :" + certificate.Subject + vbLf + "Issuer :" + certificate.Issuer)
        Catch ex As Exception
            LogLine("Error: " + ex.Message)
        End Try
        LogLine("---=== End Validate .net ===---")
    End Function
Also by EldoS: MsgConnect
Cross-platform protocol-independent communication framework for building peer-to-peer and client-server applications and middleware components.

Reply

Statistics

Topic viewed 1425 times

Number of guests: 1, registered members: 0, in total hidden: 0




|

Back to top

As of July 15, 2016 EldoS Corporation will operate as a division of /n software inc. For more information, please read the announcement.

Got it!