EldoS | Feel safer!

Software components for data protection, secure storage and transfer

Generating Certificates With Extensions

Also by EldoS: CallbackDisk
Create virtual disks backed by memory or custom location, expose disk images as disks and more.
Posted: 07/20/2006 13:33:09
by Andrei Johann (Basic support level)
Joined: 07/20/2006
Posts: 12

Hi, my name is Andrei, i am a .NET developer from Brazil, i'm trying to generating certificates with extension ... everything was ok until i needed to add a SubjectAlternativeName extension with an OtherName ...

( see code below..)

Just after I call the oCert.Generate method, the oCert.Extensions.SubjectAlternativeName.Content.Count property changes from 1 to 0, and I lose the SBUtils.Unit.UTF8ToStr(oCert.Extensions.SubjectAlternativeName.Content.Names(0).OtherName.Value) value that was "12345678901234" , and the SBUtils.Unit.OIDToStr(oCert.Extensions.SubjectAlternativeName.Content.Names(0).OtherName.OID) value that was ""
If i set other NameType of "oCert.Extensions.SubjectAlternativeName.Content.Names(0)"  than "SBX509Ext.TSBGeneralName.gnOtherName" to the SubjectAlternativeName extensions such as "SBX509Ext.TSBGeneralName.gnRFC822Name" it works well ...

When i vizualize the certificate generated with Windows Certificate MMC Console, in the SubjectAlternativeName extension, instead of presenting someting like this:

OtherName: 0e 31 32 33 34 35 36 37 38 39 30 31 32 33 34

it presents:
30 19 a0 17 06 05 60 4c   0.....`L
01 03 03 a0 0e 31 32 33   .....123
34 35 36 37 38 39 30 31   45678901
32 33 34                  234

Sorry about my English ... i'm not a native speaker, okz !

I'm testing this functionality of SecureBlackBox using the evalution version for .NET Framework 1.1 and 2.0 released at 07/20/2006

If somebody could help me solve that problem ... thankz a lot !

here is the subroutine code:
    Private Sub btnGenerateCertFinalUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerateCertFinalUser.Click
        OpenFileDialogCert.Title = "Selecione o certificado da CA para efetuar a assinatura."
        txtLOG.Text = "OPERAÇÃO: Seleção de certificado de CA para efetuar assinatura." & Chr(13) & Chr(10)
        Dim CertSelecionado As String
        Dim resultDialogCert As DialogResult = OpenFileDialogCert.ShowDialog()
        If (resultDialogCert = Windows.Forms.DialogResult.OK) Then
            CertSelecionado = OpenFileDialogCert.FileName
            txtLOG.Text &= "Certificado de CA selecionado:" & CertSelecionado & Chr(13) & Chr(10)
            txtLOG.Text &= "OPERAÇÃO CANCELADA PELO USUÁRIO" & Chr(13) & Chr(10)
            Exit Sub
        End If
            Dim objStream As Stream = File.Open(CertSelecionado, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

            Dim oCertCA As New SBX509.TElX509Certificate(Nothing)
            oCertCA.LoadFromStreamPFX(objStream, "", 0)

            txtLOG.Text &= "AGUARDE ... GERANDO CERTIFICADO DE Entidade Final" & Chr(13) & Chr(10)

            Dim oCert As New SBX509.TElX509Certificate(Nothing)
            oCert.CAAvailable = True
            oCert.ValidFrom = DateTime.Now()
            oCert.ValidTo = DateTime.Now().AddYears(4)
            oCert.SerialNumber = SBUtils.Unit.StrToUTF8(1)

            Dim Subject As New SBX509.TName
            Subject.Country = "BR"
            Subject.EMailAddress = "beltrano@diasediasparados.com.br"
            Subject.Locality = "Porto Alegre"
            Subject.StateOrProvince = "RS"
            Subject.CommonName = "DIAS e DIAS PARADOS Teste:12345678901234"


            Dim Issuer As New SBX509.TName
            Issuer.CommonName = oCertCA.IssuerName.CommonName
            Issuer.Country = oCertCA.IssuerName.Country
            'Issuer.EMailAddress = oCertCA.IssuerName.EMailAddress
            Issuer.Locality = oCertCA.IssuerName.Locality
            Issuer.Organization = oCertCA.IssuerName.Organization
            Issuer.OrganizationUnit = oCertCA.IssuerName.OrganizationUnit
            Issuer.StateOrProvince = oCertCA.IssuerName.StateOrProvince


            oCert.Extensions.Included = ceKeyUsage Or ceExtendedKeyUsage Or ceBasicConstraints Or ceCRLDistributionPoints Or ceAuthorityKeyIdentifier Or ceCertificatePolicies Or ceSubjectAlternativeName

            Dim ku As New SBX509Ext.TElKeyUsageExtension()
            ku.DigitalSignature = True
            ku.KeyEncipherment = True
            ku.NonRepudiation = True
            oCert.Extensions.KeyUsage = ku

            oCert.Extensions.ExtendedKeyUsage.ClientAuthentication = True
            oCert.Extensions.ExtendedKeyUsage.EmailProtection = True

            Dim indexSAN As Integer

            Dim CNPJ As New SBX509Ext.TElGeneralName
            CNPJ.OtherName.OID = SBUtils.Unit.StrToOID("")
            CNPJ.OtherName.Value = SBUtils.Unit.StrToUTF8("12345678901234")
            CNPJ.NameType = SBX509Ext.TSBGeneralName.gnOtherName

            indexSAN = oCert.Extensions.SubjectAlternativeName.Content.Add()

            Dim bc As New SBX509Ext.TElBasicConstraintsExtension
            bc.Critical = False
            bc.CA = False
            bc.PathLenConstraint = Nothing
            oCert.Extensions.BasicConstraints = bc

            oCert.Extensions.AuthorityKeyIdentifier.KeyIdentifier = oCertCA.Extensions.SubjectKeyIdentifier.KeyIdentifier

            oCert.Extensions.CertificatePolicies.Count = 1
            oCert.Extensions.CertificatePolicies.PolicyInformation(0).CPSURI = "http://nfe.sefaz.rs.gov.br/CA/DPC_AC_SEFAZRStesteRaiz.pdf"
            oCert.Extensions.CertificatePolicies.PolicyInformation(0).PolicyIdentifier = SBUtils.Unit.StrToOID("")

            Dim URL_CRL As New SBX509Ext.TElGeneralName
            URL_CRL.UniformResourceIdentifier = "http://nfe.sefaz.rs.gov.br/CA/AC_SEFAZRStesteRaiz.crl"
            URL_CRL.NameType = SBX509Ext.TSBGeneralName.gnUniformResourceIdentifier

            oCert.Extensions.CRLDistributionPoints.Count = 1
            Dim index As Integer
            index = oCert.Extensions.CRLDistributionPoints.DistributionPoints(0).Name.Add

            Dim signatureAlgorithm As Byte
            signatureAlgorithm = SBUtils.Unit.SB_CERT_ALGORITHM_SHA1_RSA_ENCRYPTION
            Dim PublicKeyLength As Integer = 1024

            Dim len As Integer = 4096
            Dim tmpbuf(4095) As Byte
            oCertCA.SaveKeyToBuffer(tmpbuf, len)
            Dim bufKey(len - 1) As Byte
            Dim i As Integer
            For i = 0 To len - 1
                bufKey(i) = tmpbuf(i)
            Next i

            oCert.Generate(oCertCA, signatureAlgorithm, CShort(PublicKeyLength \ 32))

            Dim CERTBytes2() As Byte = Nothing


            Dim Cer As New X509Certificate2(CERTBytes2)
            txtLOG.Text = "CERTIFICADO DE Entidade Final GERADO COM SUCESSO !"

            'SALVA EM DISCO EM FORMATO .pfx
            Dim fs As FileStream = Nothing
            Dim buf As Byte() = Nothing
            Dim sFileName As String = "C:\andrei\EntidadeFinal.pfx"
            Dim iLen As Integer = 0
            Dim sPasswd As String = ""
            buf = New Byte(-1) {}
            oCert.SaveToBufferPFX(buf, iLen, sPasswd, SBConstants.Unit.SB_ALGORITHM_PBE_SHA1_3DES, SBConstants.Unit.SB_ALGORITHM_PBE_SHA1_RC2_40)
            If iLen > 0 Then
                buf = New Byte(iLen) {}
                oCert.SaveToBufferPFX(buf, iLen, sPasswd, SBConstants.Unit.SB_ALGORITHM_PBE_SHA1_3DES, SBConstants.Unit.SB_ALGORITHM_PBE_SHA1_RC2_40)
                    fs = New FileStream(sFileName, FileMode.Create)
                    fs.Write(buf, 0, iLen)
                Catch exc As Exception
                    MessageBox.Show("Falha ao salvar o certificado: " + exc.Message, "NFe", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    If Not (fs Is Nothing) Then
                    End If
                End Try
            End If

        Catch Ex As Exception
            MessageBox.Show("Ocorreu uma exceção. ERRO:" & Ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            txtLOG.Text &= "Ocorreu uma exceção. ERRO:" & Ex.Message & Chr(13) & Chr(10)
        End Try

    End Sub
Posted: 07/20/2006 13:38:10
by Eugene Mayevski (Team)

From the first glance everything seems to be correct. Can you please send the complete test case which we can compile to support@eldos.com?

Sincerely yours
Eugene Mayevski
Posted: 07/20/2006 14:15:07
by Andrei Johann (Basic support level)
Joined: 07/20/2006
Posts: 12

Sure !

Thanks for your attention !

I'll send you the complete .NET 2005 Visual Studio Solution .. and a certificate whose content i'm trying to "imitate" ..

[ Download ]
Posted: 07/20/2006 14:16:50
by Andrei Johann (Basic support level)
Joined: 07/20/2006
Posts: 12

Here is the certificate ...

[ Download ]
Posted: 07/20/2006 14:54:09
by Eugene Mayevski (Team)

My bad. I could have guessed freom the beginning, but decided to test and just wasted time.

You are setting the value incorrectly. The binary value of any extension must be properly formatted as an ASN.1 sequence. You can use the following code:

CNPJ.OtherName.OID = SBUtils.Unit.StrToOID("")
            CNPJ.OtherName.Value = SBMessages.Unit.FormatAttributeValue(SBASN1Tree.Unit.SB_ASN1_VISIBLESTRING, SBUtils.Unit.BytesOfString("12345678901234"))

Note, that the type of the value (VISIBLESTRING in my sample) is determined by the OID, i.e. you must know the type yourself.

Sincerely yours
Eugene Mayevski
Posted: 07/20/2006 15:12:51
by Andrei Johann (Basic support level)
Joined: 07/20/2006
Posts: 12

It worked ! Thank you, Eugene!

congratulations for the excellent support !

Also by EldoS: Callback File System
Create virtual file systems and disks, expose and manage remote data as if they were files on the local disk.



Topic viewed 5273 times

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


Back to top

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

Got it!