參考討論文: https://stackoverflow.com/questions/256405/programmatically-create-x509-certificate-using-openssl
// sudo apt-get install libcrypto
// g++ genrsa.c -lcrypto && ./a.out
// genrsa.c
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <stdio.h>
int main( ) {
int nbits = 2048;
RSA *rsaKey = RSA_new();
BIGNUM *bignF4 = BN_new();
BN_set_word(bignF4, 0x10001);// bignF4 = 65537
if (RSA_generate_key_ex(rsaKey, nbits, bignF4, NULL)) {
long days = 365;
unsigned char* subj[3] = {
(unsigned char *)"TW",
(unsigned char *)"SELF",
(unsigned char *)"0.0.0.0"
};
X509 *certify = X509_new();
X509_set_version(certify, 2);// Ver 3
ASN1_INTEGER_set(X509_get_serialNumber(certify), 1);
X509_gmtime_adj(X509_get_notBefore(certify), 0);
X509_gmtime_adj(X509_get_notAfter(certify), days * 86400);
X509_NAME *subjName = X509_get_subject_name(certify);
X509_NAME_add_entry_by_txt(subjName, "C" , MBSTRING_ASC, subj[0], -1, -1, 0);
X509_NAME_add_entry_by_txt(subjName, "O" , MBSTRING_ASC, subj[1], -1, -1, 0);
X509_NAME_add_entry_by_txt(subjName, "CN", MBSTRING_ASC, subj[2], -1, -1, 0);
X509_set_issuer_name(certify, subjName);
EVP_PKEY *keyPair = EVP_PKEY_new();
EVP_PKEY_assign_RSA(keyPair, rsaKey);
X509_set_pubkey(certify, keyPair);
X509_sign(certify, keyPair, EVP_sha1());
FILE *fout = fopen("private.pem", "wb");
PEM_write_PrivateKey(fout, keyPair, NULL, NULL, 0, NULL, NULL);
fclose(fout);
EVP_PKEY_free(keyPair);
fout = fopen("certify.pem", "wb");
PEM_write_X509(fout, certify);
fclose(fout);
X509_free(certify);
}
BN_free(bignF4);
RSA_free(rsaKey);
return 0;
}
沒有留言:
張貼留言