求可实现DER编码ASN.1 DN与ASCII字符串互转的API/C程序
Absolutely! There are several robust libraries and approaches to handle bidirectional conversion between DER-encoded ASN.1 Distinguished Names (DNs) and ASCII string formats in C. Let’s break down the most reliable options:
1. OpenSSL (Industry-Standard Choice)
OpenSSL has comprehensive built-in functions for X.509 DN handling, which covers exactly this use case. Here’s how to implement both directions:
ASCII String to DER-encoded DN
#include <openssl/x509.h> #include <openssl/asn1.h> int ascii_to_der_dn(const char *ascii_dn, unsigned char **der_out, int *der_len) { X509_NAME *name = X509_NAME_new(); if (!name) return 0; // Parse a full ASCII DN (e.g., "CN=John Doe,OU=Engineering,O=Example Corp,C=US") if (X509_NAME_parse(name, ascii_dn) != 1) { X509_NAME_free(name); return 0; } // Encode the parsed DN to DER format *der_len = i2d_X509_NAME(name, der_out); X509_NAME_free(name); return (*der_len > 0) ? 1 : 0; }
DER-encoded DN to ASCII String
#include <openssl/x509.h> #include <openssl/asn1.h> char *der_to_ascii_dn(const unsigned char *der_in, int der_len) { X509_NAME *name = d2i_X509_NAME(NULL, &der_in, der_len); if (!name) return NULL; // Convert the DN to a one-line ASCII string following RFC 4514 char *ascii_dn = X509_NAME_oneline(name, NULL, 0); X509_NAME_free(name); return ascii_dn; }
Note: Don’t forget to link against OpenSSL when compiling with -lcrypto.
2. Libtasn1 (Lightweight GNU Alternative)
If you prefer a smaller, focused ASN.1 library, Libtasn1 is a solid pick. It requires a bit more manual setup but is ideal for embedded or minimal-dependency environments:
- First, load the ASN.1 definition for
Name(from the X.509 specification) usingasn1_parser2tree(). - Use
asn1_der_decoding()to parse DER data into a structured representation. - To go from ASCII to DER, populate the ASN.1 structure with your DN values (mapping attribute names to OIDs) and use
asn1_der_encoding()to generate the final DER bytes.
3. Custom Implementation (For Strict Dependency Constraints)
If you can’t rely on external libraries, you can implement the ASN.1 DER logic yourself—but this is not recommended unless absolutely necessary. You’ll need to:
- Understand the DN structure: a sequence of Relative Distinguished Names (RDNs), each containing one or more Attribute-Value pairs.
- Implement DER’s tag-length-value (TLV) encoding rules, including OID parsing/encoding and handling different string types (UTF8String, PrintableString, etc.).
This approach is error-prone and time-consuming, so stick to mature libraries whenever possible.
Key Notes
- Ensure your ASCII DN follows RFC 4514 format (comma-separated RDNs, standard attribute abbreviations like
CNfor CommonName). - DER encoding must comply with RFC 5280 (X.509 certificate specs) to be interoperable with other systems.
内容的提问来源于stack exchange,提问作者user3553315

