EldoS | Feel safer!

Software components for data protection, secure storage and transfer

Invalid self-signed certificate generated

Also by EldoS: MsgConnect
Cross-platform protocol-independent communication framework for building peer-to-peer and client-server applications and middleware components.
Posted: 06/02/2006 08:39:26
by Stephane Grobety (Priority Standard support level)
Joined: 04/18/2006
Posts: 173


I need to generate certificates for HTTPS client authentication using SecureBlackBox on Delphi 6. I wrote an application to do so but every certificate I generated using this had invalid properties. So I tried it with the CertDemo sample provided with SBB and I got the same result.

The certificate looks almost fine when I check it from within CertDemo but it looks wrong when viewed with the built-in certificate viewer of Windows XP Pro.

I'm attaching a sample of the certificate generated with the certDemo application. The cert I generate with my own code is roughly the same except that I need to add key usage, extended key usage and serial number to my certificate and nothing looks like it should).

Parameters used to generate that certificate:
Key: RSA/SHA1 1024
Country: Switzerland
State: Geneva
Locality: Accacias
Organisation: GIT
Command name: test
Validity: from 02/06/2006 to 02/06/2007

What's the cause of this behavior ?

[ Download ]
Posted: 06/02/2006 09:02:53
by Ken Ivanov (Team)

The certificate itself is correct, the signature is good. The only thing that may confuse certificate viewer is that subject and issuer fields are stored as ASN.1 OCTETSTRING values (usually these values are stored as PRINTABLESTRINGs).

Most likely, you are using SubjectRDN and IssuerRDN properties to specify issuer and subject parameters. To make ElX509Certificate store these parameters as PRINTABLESTRINGs, you should set the corresponding TElRelativeDistinguishedName.Tags[] property accordingly, e.g.:

Cert.SubjectRDN.Values[0] := 'test';
Posted: 06/02/2006 10:00:04
by Stephane Grobety (Priority Standard support level)
Joined: 04/18/2006
Posts: 173

Thanks, that solved it.

Now, I'm missing my key usage and extended key usage. I'm using the following code to set these properties, is there anything wrong with it ?

    ACertificate.Extensions.KeyUsage.DigitalSignature := true;
    ACertificate.Extensions.KeyUsage.KeyEncipherment := true;
    ACertificate.Extensions.ExtendedKeyUsage.ClientAuthentication := true;
Posted: 06/02/2006 10:04:33
by Ken Ivanov (Team)

You should also set the Included property accordingly:
ACertificate.Extensions.Included := [ceKeyUsage];
Posted: 06/02/2006 10:50:46
by Stephane Grobety (Priority Standard support level)
Joined: 04/18/2006
Posts: 173

Thanks. I thought I was missing something: it works perfectly now.
Posted: 07/20/2006 13:28:29
by Andrei Johann (Basic support level)
Joined: 07/20/2006
Posts: 12

Generating Certificates With Extensions

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
Also by EldoS: CallbackRegistry
A component to monitor and control Windows registry access and create virtual registry keys.



Topic viewed 5787 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!