test.c 1.58 KB
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.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 = 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(void **state){
    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;
        }
    }
    assert_true(same);

    (void)state;
}

int main(void){
    srand(time(NULL));
    cmocka_set_message_output(CM_OUTPUT_XML);
    const struct CMUnitTest test_group[]={
        cmocka_unit_test(rsa_normal_test)
    };

    return cmocka_run_group_tests(test_group,NULL,NULL);
}