std::unique_ptr generateCSR()

in azure-protected-vm-secrets/Linux/OsslX509.cpp [97:125]


std::unique_ptr<X509_REQ, decltype(&X509_REQ_free)> generateCSR(EVP_PKEY* pkey, const std::string& commonName) {
   std::unique_ptr<X509_REQ, decltype(&X509_REQ_free)> req(X509_REQ_new(), &X509_REQ_free);
   std::unique_ptr<X509_NAME, decltype(&X509_NAME_free)> name(X509_NAME_new(), &X509_NAME_free);
   // Set the subject name fields
    if (!X509_NAME_add_entry_by_txt(name.get(), "C", MBSTRING_ASC,
       (const unsigned char*)"US", -1, -1, 0)) {
         throw OsslError(ERR_get_error(), "Failed to set country");
    }
    if (!X509_NAME_add_entry_by_txt(name.get(), "ST", MBSTRING_ASC,
        (const unsigned char*)"State", -1, -1, 0)) {
        throw OsslError(ERR_get_error(), "Failed to set state");
    }
    if (!X509_NAME_add_entry_by_txt(name.get(), "O", MBSTRING_ASC,
        (const unsigned char*)"Organization", -1, -1, 0)) {
        throw OsslError(ERR_get_error(), "Failed to set organization");
    }
    if (!X509_NAME_add_entry_by_txt(name.get(), "CN", MBSTRING_ASC,
        (const unsigned char*)commonName.c_str(), -1, -1, 0)) {
        throw OsslError(ERR_get_error(), "Failed to set common name");
    }
    if (!X509_REQ_set_subject_name(req.get(), name.get()) 
        || !X509_REQ_set_pubkey(req.get(), pkey)) {
        throw OsslError(ERR_get_error(), "Failed to set subject name or public key");
    }
    if (!X509_REQ_sign(req.get(), pkey, EVP_sha256())) {
        throw OsslError(ERR_get_error(), "Failed to sign CSR");
    }
    return req;
}