Last active
December 26, 2019 06:45
-
-
Save devendranaga/e008a4540a80d232d4ca2a78a3b78603 to your computer and use it in GitHub Desktop.
generate RSA key pair and write them to a file (openssl)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Devendra Naga (devendra.aaru@gmail.com) | |
* License: MIT | |
* Code failure paths are not taken care.. this program is only for demonstration purposes | |
*/ | |
#include <stdio.h> | |
#include <openssl/rsa.h> | |
#include <openssl/evp.h> | |
#include <openssl/pem.h> | |
int main() | |
{ | |
char *pubkey = "./rsa_2048.key"; | |
char *privkey = "./rsa_2048_p.key"; | |
EVP_PKEY_CTX *ctx; | |
ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); | |
if (!ctx) { | |
return -1; | |
} | |
int ret; | |
ret = EVP_PKEY_keygen_init(ctx); | |
if (ret != 1) { | |
return -1; | |
} | |
ret = EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048); | |
if (ret != 1) { | |
return -1; | |
} | |
EVP_PKEY *key; | |
ret = EVP_PKEY_keygen(ctx, &key); | |
if (ret != 1) { | |
return -1; | |
} | |
FILE *fp = fopen(privkey, "w"); | |
if (!fp) { | |
return -1; | |
} | |
ret = PEM_write_PrivateKey(fp, key, NULL, NULL, 0, NULL, NULL); | |
if (ret != 1) { | |
return -1; | |
} | |
fclose(fp); | |
fp = fopen(pubkey, "w"); | |
if (!fp) { | |
return -1; | |
} | |
ret = PEM_write_PUBKEY(fp, key); | |
if (ret != 1) { | |
return -1; | |
} | |
fclose(fp); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment