#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include "aes_util.h"
#include "base64.h"
#include "kydoctor_crypt.h"
 
const unsigned char KEY[16] = "0123456789ABCDEF";
const unsigned char IV[16] = {
        0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0,
        0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0
};
 

long get_file_size(FILE *stream)
{
    long file_size = -1;
    long cur_offset = ftell(stream);
    if (cur_offset == -1) {
        printf("ftel fail\n");
        return -1;
    }
    if (fseek(stream, 0, SEEK_END) != 0) {
        printf("fseek fail\n");
        return -1;
    }

    file_size = ftell(stream);
    if (file_size == -1) {
        printf("ftell failed\n");
    }
    if (fseek(stream, cur_offset, SEEK_SET) != 0) {
        printf("fseek failed\n");
        return -1;
    }

    return file_size;
}

int main(int argc, char **argv) {
    //unsigned char in[] = "hello world";
    //orig
    //int in_len = sizeof(in);
 
    unsigned char in[4096] = {0};
    memset(in, 0xAA, 4096);
    int in_len = 4096;

#if 1
    //00-测试加密一段内存数据
    printf("=============00-测试加密一段内存数据============\n");
    unsigned int out_len = 0;
    unsigned char *deb64_orig_data = kydoctor_encrypt(in, in_len, &out_len, KEY, IV);
    printBuf(deb64_orig_data, out_len);

    unsigned int out_len2 = 0;
    unsigned char *out_decrypted = kydoctor_decrypt(deb64_orig_data, out_len, &out_len2, KEY, IV);
    printBuf(out_decrypted, out_len2);

    free(deb64_orig_data);
    free(out_decrypted);

#else

    //encrypt
    unsigned int out_len = 0;
    unsigned char *out = encrypt(in, in_len, &out_len, KEY, IV);
    printBuf(out, out_len);
 
    //base64 encode
    char *b64_cipher_text = b64_encode(out, out_len);
    printf("base64 result:\t%s\n", b64_cipher_text);
 
    //base64 decode
    size_t de_size = 0;
    unsigned char *deb64_orig_data = b64_decode_ex(b64_cipher_text, strlen(b64_cipher_text), &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);
 
    free(out);
    free(b64_cipher_text);
    free(deb64_orig_data);
    free(out_decrypted);
 #endif

    return EXIT_SUCCESS;
}