#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include "aes_util.h"
#include "base64.h"
#include "kydoctor_crypt.h"

void printBuf(const unsigned char *buf, unsigned int len) {
    printf("buf len :%d\n", len);
	printf("output hex\n");
    for (unsigned int i = 0; i < len; i++) {
        printf("%02x, ", *(buf + i));
    }
    printf("\n");
	printf("output string\n");
	for (unsigned int i = 0; i < len; i++) {
        printf("%c", *(buf + i));
    }
    printf("\n");
}

unsigned char *kydoctor_encrypt(const unsigned char *in, int in_len, unsigned int *out_len,
                       const unsigned char *key, const unsigned char *iv)
{
    //encrypt
    unsigned int aes_out_len = 0;
    unsigned char *out = encrypt(in, in_len, &aes_out_len, key, iv);
    //printBuf(out, aes_out_len);
 
    //base64 encode
    char *b64_cipher_text = b64_encode(out, aes_out_len);
    //printf("base64 result:\t%s\n", b64_cipher_text);
    *out_len = strlen(b64_cipher_text);
    //printf("---> out_len:%d\n", *out_len);
    free(out);
    
    return b64_cipher_text;
}

unsigned char *kydoctor_decrypt(const unsigned char *in, int in_len, unsigned int *out_len,
                       const unsigned char *key, const unsigned char *iv)
{
    //base64 decode
    size_t de_size = 0;
    unsigned char *deb64_orig_data = b64_decode_ex(in, strlen(in), &de_size);
 
    //decrypt
    unsigned int out_len2 = 0;
    unsigned char *out_decrypted = decrypt(deb64_orig_data, de_size, &out_len2, key, iv);
    //printBuf(out_decrypted, out_len2);
    *out_len = out_len2;
    
    free(deb64_orig_data);
    
    return out_decrypted;
}