openssl rsa key 생성 example code

본 글은 openssl 라이브러리를 사용해 rsa 키를 생성하는 예제 소스를 싣고 있다.
rsa 키는 openssl 라이브러리 빌드 후 만들어지는 openssl app을 사용해 생성 할 수도 있다.
아래는 RSA_generate_key api를 사용해 rsa 키를 만들고, BIO 함수들을 사용해 PublicKey/PrivateKey 파일에 저장하는 예를 보여주고 있다.

[소스 코드]

#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/rand.h>

BIO *publickey_bio = NULL;  
BIO *privatekey_bio = NULL; 
BIO *stdout_bio = NULL;   

void closefiles();

int openfiles(int isPEMFromat)
{
stdout_bio = BIO_new(BIO_s_file());
if(stdout_bio)
BIO_set_fp(stdout_bio, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
publickey_bio = BIO_new(BIO_s_file());
privatekey_bio = BIO_new(BIO_s_file());

if(publickey_bio == NULL || privatekey_bio == NULL)
{
closefiles();
return -1;
}

if(isPEMFromat)
{
if(BIO_write_filename(publickey_bio, "./PublicKey.pem") <= 0)
{
closefiles();
return -1;
}

if(BIO_write_filename(privatekey_bio, "./PrivateKey.pem") <= 0)
{
closefiles();
return -1;
}
}
else
{
if(BIO_write_filename(publickey_bio, "./PublicKey.dem") <= 0)
{
closefiles();
return -1;
}

if(BIO_write_filename(privatekey_bio, "./PrivateKey.dem") <= 0)
{
closefiles();
return -1;
}
}

return 0;     
}

int writefiles(RSA *rsa,int isPEMFromat)
{
if(isPEMFromat) 
{
if(!PEM_write_bio_RSA_PUBKEY(stdout_bio, rsa)) 
{
return -1;
}   
if(!PEM_write_bio_RSA_PUBKEY(publickey_bio, rsa)) 
{
return -1;
}
if(!PEM_write_bio_RSAPrivateKey(stdout_bio, rsa, NULL, NULL, 0, NULL, NULL))
{
return -1;
}

if(!PEM_write_bio_RSAPrivateKey(privatekey_bio, rsa, NULL, NULL, 0, NULL, NULL))
{
return -1;
}
}
else
{  
if(!i2d_RSA_PUBKEY_bio(stdout_bio, rsa)) 
{
return -1;
}

if(!i2d_RSA_PUBKEY_bio(publickey_bio, rsa))
{
return -1;
}
if(!i2d_RSAPrivateKey_bio(stdout_bio, rsa))
{
return -1;
}

if(!i2d_RSAPrivateKey_bio(privatekey_bio, rsa))
{
return -1;
}
}
}

void closefiles()
{
if(publickey_bio) BIO_free_all(publickey_bio);
if(privatekey_bio) BIO_free_all(privatekey_bio);
if(stdout_bio) BIO_free_all(stdout_bio);
}


RSA *gen_key(int key_len)
{
RAND_status();
return RSA_generate_key(key_len, RSA_F4, NULL, NULL);
}

int main(int argc, char** argv)
{
    int i = 0;
    RSA *rsa = NULL;   

    int key_len = 4096;   
    int isPEMFromat = 1;
    
    if(argv[1] != 0)
{
key_len = atoi(argv[1]);
}


rsa = gen_key(key_len);
if(rsa)
{
if(openfiles(isPEMFromat) == 0)
{
writefiles(rsa, isPEMFromat);
closefiles();
}

RSA_free(rsa);
}
    
      
    return 0;
}


[빌드]
gcc -o rsakeygen rsakeygen.c -lssl -lcrypto

[실행 결과]



[관련 포스트]

댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

python winsound를 이용한 윈도우 환경에서 소리 재생 예제

mkfs.fat Device or resource busy 에러 해결법

Embedded Linux USB Ethernet Gadget 사용하기