main.c 1.44 KB
//
// Created by 강현태 on 06/10/2018.
//

#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <string.h>

#include <stdio.h>
#include <openssl/rsa.h>

#define ASCII_START 32
#define ASCII_END 126

char* generateRandomString(int size) {
    int i;
    char *res = (char*)malloc(size + 1);
    for(i = 0; i < size; i++) {
        res[i] = (char) (rand()%(ASCII_END-ASCII_START))+ASCII_START;
    }
    res[i] = '\0';
    return res;
}

static void rsa_normal_test(){
    int i;
    int bits = 2048; //key size
    int buflen = 1024; //buffer suze
    unsigned char *plaintext, *ciphertext, *randomstring;
    int same;
    BIGNUM *bn = BN_new();
    BN_set_word(bn, RSA_F4);


    //1. rsa구조체 생성
    RSA *rsa = RSA_new();

    //2. key pair(private,public) 생성
    RSA_generate_key_ex(rsa, bits, bn, NULL);

    //3. 본인의 public key로 암호화.
    randomstring=plaintext=(unsigned char*)generateRandomString(buflen);
    RSA_public_encrypt(buflen, plaintext, ciphertext, rsa,RSA_PKCS1_OAEP_PADDING);

    //4. 본인의 private key로 복호화.
    RSA_private_decrypt(buflen, ciphertext, plaintext, rsa,RSA_PKCS1_OAEP_PADDING);

    //5. 원 평문과 일치하는지 확인
    same = 1;
    for(i=0;i<buflen;i++){
        if(plaintext[i]!=randomstring[i]){
            same=0;
            break;
        }
    }
    printf("%s \n",(same==1)?"통과":"다름");

}

int main(void){
    srand(time(NULL));
    rsa_normal_test();
}