使用OpenSSL API添加自定义扩展的X509v3证书CSR签发问题
Hey there! Let’s walk through your OpenSSL code for adding a custom extension to a CSR, and go over some key points to refine it, plus notes on what might be going on with your issued certificate.
First off, your core approach is solid—you’re creating a custom OID, building the extension, and attaching it to the CSR. Here are some tweaks to make it more robust:
Fix Memory Leaks: OpenSSL doesn’t handle automatic garbage collection, so you’re leaving several objects hanging around after use. Add cleanup code once you’re done with the extension stack and string:
// After calling X509_REQ_add_extensions(x, exts); sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); ASN1_OCTET_STRING_free(os);This prevents memory leaks, especially if your code runs repeatedly (like in a service).
Avoid Duplicate OID Registration: Using
OBJ_create()registers the OID globally. If your code runs multiple times, this will throw an error when trying to re-register the same OID. Check if it exists first:int nid = OBJ_txt2nid("CompanyName"); if (nid == NID_undef) { // Only create if it doesn't already exist nid = OBJ_create("2.5.29.41", "CompanyName", "Company Name"); }Also, a quick heads-up: the
2.5.29arc is for standard X.509 extensions. Using an unassigned OID here might cause validation issues down the line—make sure you have the right to use this OID for your organization.Safer String Length: You hardcoded
8for "ABC Corp"’s length, which works now, but it’s easy to break if you change the company name later. Usestrlen()instead:ASN1_OCTET_STRING_set(os, "ABC Corp", strlen("ABC Corp"));Critical Extension Flag: You set the
critparameter to0(non-critical) inX509_EXTENSION_create_by_NID(). That’s totally fine unless you need relying parties to process this extension—if you do, flip that to1.
Since you’ve already received the signed certificate, the good news is your CSR was processed correctly! If you’re noticing the custom extension is missing from the final cert, it’s likely the CA’s policy strips unrecognized non-critical extensions. You’ll need to check with your CA to see if they support including custom extensions, or if you need to submit a request to enable that.
内容的提问来源于stack exchange,提问作者Ajay

