Table of Contents
Question content
Solution
Home Backend Development Golang Generate subject name from x509 certificate in string format

Generate subject name from x509 certificate in string format

Feb 11, 2024 am 10:00 AM
standard library

从字符串格式的 x509 证书生成主题名称

php Editor Strawberry Generating the subject name from the x509 certificate in string format is an important operation, which can help developers extract key information from the certificate. By parsing the x509 certificate in string format, we can obtain the subject name of the certificate, including the issuer, validity period, public key and other information of the certificate. This process is important for building secure network communications, verifying the legitimacy of certificates, and protecting user privacy. In PHP, we can use the functions provided by the OpenSSL extension to implement this function and handle x509 certificates simply and efficiently.

Question content

I am trying to generate the distinguished name from x509.certificate.

The format I expect is:

"cn=<common_name>,ou=<org_unit>,o=,dnqualifier=+7he5grzxim+lkemb5fs98e+fpy="
Copy after login

(I replaced some values ​​with labels)

With my code, I get the expected string without the dnqualifier part, like this:

cn=<common_name>,ou=<org_unit>,o=,2.5.4.46=#131c537771614a5531514c2449444e4846373755547a1f5749653955303d"
Copy after login

it's here, 2.5.4.46 is the asn.1 object id of "dnqualifier" Reference: Link The value looks like a hexadecimal string.

Is there a standard way (or a simple workaround) to get the distinguished name in the expected format? That is, the text "dnqualifier" should appear instead of its objectidentifier, and the actual string value should appear instead of hexadecimal.

My code looks like this:

package main

import (
    "crypto/x509"
    "encoding/pem"
    "fmt"

    "github.com/sirupsen/logrus"
)

func main() {

    cert := "" // certificate string here
    block, rest := pem.decode([]byte(cert))
    if len(rest) != 0 {
        logrus.error("certificate string not fully decoded : ", rest)
    }

    certificate, err := x509.parsecertificate(block.bytes)
    if err != nil {
        logrus.witherror(err).error("error parsing certificate")
    }

    fmt.println(certificate.subject.string())
}

Copy after login

From this code certificate.subject.string() the output given is as follows: cn=<common_name>,ou=<org_unit>,o=<org>,2.5.4.46=#131c537771614a5531514c2449444e4846373755547a1f5749653955303d"

in addition,

fmt.printf("%+v\n", cert.subject.tordnsequence())
Copy after login

and

var sub pkix.RDNSequence
asn1.Unmarshal(certificate.RawSubject, &sub)
Copy after login

Neither helps.

Solution

The standard library only provides a limited list of attributes:

var attributetypenames = map[string]string{
    "2.5.4.6":  "c",
    "2.5.4.10": "o",
    "2.5.4.11": "ou",
    "2.5.4.3":  "cn",
    "2.5.4.5":  "serialnumber",
    "2.5.4.7":  "l",
    "2.5.4.8":  "st",
    "2.5.4.9":  "street",
    "2.5.4.17": "postalcode",
}
Copy after login

For other properties, it just uses the object identifier as the name and encodes the value as a hexadecimal string where possible (see (rdnsequence).string):

oidstring := tv.type.string()
typename, ok := attributetypenames[oidstring]
if !ok {
    derbytes, err := asn1.marshal(tv.value)
    if err == nil {
        s += oidstring + "=#" + hex.encodetostring(derbytes)
        continue // no value escaping necessary.
    }

    typename = oidstring
}

valuestring := fmt.sprint(tv.value)
escaped := make([]rune, 0, len(valuestring))
Copy after login

It does not provide any knobs for us to get customized strings. So we have to do it ourselves.

I suggest listing the properties we want and appending them to the string returned from certificate.subject.tordnsequence().string(). like this:

package main

import (
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "fmt"
)

func tostring(name pkix.name) string {
    s := name.tordnsequence().string()

    // list the extra attributes that should be added.
    attributetypenames := map[string]string{
        "2.5.4.43": "initials",
        "2.5.4.46": "dnqualifier",
    }

    for typ, typename := range attributetypenames {
        for _, atv := range name.names {
            oidstring := atv.type.string()
            if oidstring == typ {
                // to keep this demo simple, i just call fmt.sprint to get the string.
                // maybe you want to escape some of the characters.
                // see https://github.com/golang/go/blob/1db23771afc7b9b259e926db35602ecf5047ae23/src/crypto/x509/pkix/pkix.go#l67-l86
                s += "," + typename + "=" + fmt.sprint(atv.value)
                break
            }
        }
    }
    return s
}

func main() {
    block, _ := pem.decode([]byte(cert))
    certificate, err := x509.parsecertificate(block.bytes)
    if err != nil {
        panic(err)
    }

    fmt.println(certificate.subject.string())
    fmt.println()
    fmt.println(certificate.subject.tordnsequence().string())
    fmt.println()
    fmt.println(tostring(certificate.subject))
}

var cert = `-----begin certificate-----
miigvdccbksgawibagiupminkycv6nqggfhrq1sj/y/4gykwdqyjkozihvcnaqel
bqawgfsxgzazbgnvbammennly3vyzs5legftcgxllmnvbtelmakga1uebhmcwfgx
etapbgnvbacmcez1bibmyw5kmsgwjgydvqqkdb9neunviexmqybmveqgsu5dichk
lmiuys4gt3vyq28pmriweaydvqqldaltu0wgrgvwdc4xczajbgnvbagmallzmsqw
igyjkozihvcnaqkbfhvzc2wtywrtaw5azxhhbxbszs5jb20xetapbgnvbckmcepv
ag4grg9lmqwwcgydvqqedaneb2uxdtalbgnvbcombepvag4xddakbgnvbcsma0py
rdenmasga1uelhmec29tztaefw0ymza2mtixndi2mzhafw0ynda2mtexndi2mzha
mih7mrswgqydvqqddbjzzwn1cmuuzxhhbxbszs5jb20xczajbgnvbaytalhymrew
dwydvqqhdahgdw4gtgfuzdeomcyga1uecgwftxldbybmtemgtfreieloqyaozc5i
lmeuie91cknvktesmbaga1uecwwju1nmierlchqumqswcqydvqqidajzwtekmcig
csqgsib3dqejaryvc3nslwfkbwluqgv4yw1wbguuy29tmrewdwydvqqpdahkb2hu
iervztemmaoga1uebawdrg9lmq0wcwydvqqqdarkb2humqwwcgydvqqrdankweqx
dtalbgnvbc4tbhnvbwuwggiima0gcsqgsib3dqebaquaa4icdwawggikaoicaqdl
i0xuep6r94lf5yn0lqni2qljtf4yiuapwsph1g6jutldcr5f70bkaxagznzkxssb
rgu+zwviphu1kilnx1youhfdzdx0ecmayw22zet4p8f88slnmhquxixjypopo+2b
hz8u1by7ojdccw94jhmhbug07whiu8y54wijgjv3xwnvgaorjtxs3csubmldfki7
s9gfgvqpokqpbbl+v37vbvkzgs3bw4lf7apyqe9q63q2held8/aabatujhgn1bzs
truvda9fkktdlvkn6furaeccdc+eaonpsxwimp/d01wukofojywmbgbm7a/bpby0
uxyqwmkxztquxd8mdaev89oao4ijuo8q50+9xehtb/q4tdhzjjw5k6xxqfxatrqa
/xmn8fmitvddirxqaz4ttvpdeqxnudh3retzbgoqzy4mqcgzv723tdbfzlgiqnif
1atjueotmbl7juj/1qulrpb+/ayzgqrg0xlpjr3h1essebn1ts8elvk5z6ekp5ur
rjlv3z2qq1vsn/ngnqkviyeppwj1wgxkkmaz3d6i3gixqpmklno2wdorwf/m+opu
c5+bl8nhpc0hirodi8vnkbj5mimqazwfnfhq1vveihkzxfeuee8y1r7ju/mo5qd1
z6wato77vcqd2g1xgqdjy7hrzgvmx/m9rrhqe57gyqidaqabozywndatbgnvhsue
ddakbggrbgefbqcdatadbgnvhq4efgqu8wifqbhufesmbdsbjclj4zhcynewdqyj
kozihvcnaqelbqadggibafx4qapmwkzd6juofcdmdxynjzlgyu0vtosjaor5vck8
qk/rhpqmg/j+eoikjy+xyh72wuovp25z2c99gyeyx3ve2ttsqq9uhz5eeonvi4h5
em68s5hwpywwo2u5fsvcofmpbeft/vtuvt+jczpxvrzz3a9zbwkapivoclp5y9ik
slzrkbvosafanfeffk/kyootrnoe/ahpezua8efkrlh4ggp8nzzcjamwwaoqkf3o
hufizyaenja6sm37id3eqwvsrtwkrrdkci6nqcpf0tpvxwazist2+tyimbuhacq7
qc1vhul9oyabhgjkgvhqsxxuybobqaoxdvmjueapdzgzfljlpari7aao1vamft1/
+4ulio1p9egkqdtzuu4grvbwo1pftj/alp2o/b/fnecevlphnlast+frldymrnsz
r3uv47pzpuka1+zivmpkk0kwjcb1xdficpj0t9uc7bmueyrxkf9zytbf9iqzlfnl
1lrxdod7/tf/gjlwbtiei8gwi38fimhy6iawl2epk1gzq3wep0km/lx6ol5dgmrr
2sbczecqhzvb7ya7k28iff2wma9txl/nbdhw57/7bclkbevaniwgvuqroggrmlxg
z1xp51mthl8bl2zn+q4x7xjvfvxbetfwxa8b9vlho1qkdzcdrgzt5jebpm5zgj5k
-----end certificate-----`
Copy after login

Output:

CN=secure.example.com,OU=SSL Dept.,O=MyCo LLC LTD INC (d.b.a. OurCo),L=Fun Land,ST=YY,C=XX,2.5.4.46=#1304736f6d65,2.5.4.43=#13034a5844,2.5.4.42=#13044a6f686e,2.5.4.4=#1303446f65,2.5.4.41=#13084a6f686e20446f65,1.2.840.113549.1.9.1=#0c1573736c2d61646d696e406578616d706c652e636f6d

CN=secure.example.com,OU=SSL Dept.,O=MyCo LLC LTD INC (d.b.a. OurCo),L=Fun Land,ST=YY,C=XX

CN=secure.example.com,OU=SSL Dept.,O=MyCo LLC LTD INC (d.b.a. OurCo),L=Fun Land,ST=YY,C=XX,initials=JXD,dnQualifier=some
Copy after login

The above is the detailed content of Generate subject name from x509 certificate in string format. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use absolute value in c++ How to use absolute value in c++ May 06, 2024 pm 06:15 PM

There are two ways to obtain absolute values ​​in C++: 1. Use the built-in function abs() to obtain the absolute value of an integer or floating point type; 2. Use the generic function std::abs() to obtain various supported absolute values. Operates on absolute values ​​of data types.

How to use std:: in c++ How to use std:: in c++ May 09, 2024 am 03:45 AM

std is the namespace in C++ that contains components of the standard library. In order to use std, use the "using namespace std;" statement. Using symbols directly from the std namespace can simplify your code, but is recommended only when needed to avoid namespace pollution.

What does prime mean in c++ What does prime mean in c++ May 07, 2024 pm 11:33 PM

prime is a keyword in C++, indicating the prime number type, which can only be divided by 1 and itself. It is used as a Boolean type to indicate whether the given value is a prime number. If it is a prime number, it is true, otherwise it is false.

_complex usage in c language _complex usage in c language May 08, 2024 pm 01:27 PM

The complex type is used to represent complex numbers in C language, including real and imaginary parts. Its initialization form is complex_number = 3.14 + 2.71i, the real part can be accessed through creal(complex_number), and the imaginary part can be accessed through cimag(complex_number). This type supports common mathematical operations such as addition, subtraction, multiplication, division, and modulo. In addition, a set of functions for working with complex numbers is provided, such as cpow, csqrt, cexp, and csin.

What does fabs mean in c++ What does fabs mean in c++ May 08, 2024 am 01:15 AM

The fabs() function is a mathematical function in C++ that calculates the absolute value of a floating point number, removes the negative sign and returns a positive value. It accepts a floating point parameter and returns an absolute value of type double. For example, fabs(-5.5) returns 5.5. This function works with floating point numbers, whose accuracy is affected by the underlying hardware.

What does config mean in java? What does config mean in java? May 07, 2024 am 02:39 AM

Config represents configuration information in Java and is used to adjust application behavior. It is usually stored in external files or databases and can be managed through Java Properties, PropertyResourceBundle, Java Configuration Framework or third-party libraries. Its benefits include decoupling and flexibility. , environmental awareness, manageability, scalability.

How to calculate absolute value in c++ How to calculate absolute value in c++ May 06, 2024 pm 06:21 PM

There are three ways to find the absolute value in C++: Using the abs() function, you can calculate the absolute value of any type of number. Using the std::abs() function, you can calculate the absolute value of integers, floating point numbers, and complex numbers. Manual calculation of absolute values, suitable for simple integers.

What does min mean in c++ What does min mean in c++ May 08, 2024 am 12:51 AM

The min function in C++ returns the minimum of multiple values. The syntax is: min(a, b), where a and b are the values ​​to be compared. You can also specify a comparison function to support types that do not support the < operator. C++20 introduced the std::clamp function, which handles the minimum of three or more values.

See all articles