#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ctf.h"

#define ENCRYPT_PIC "encrypt_png.dat"
#define NORMAL_PIC "bg.png"
#define DECRYPT_PIC "decrypt.png"

void main(){

    unsigned char _xorKey[16],_key[17],* _pngBuffer,*_dat_magic,*_png_magic;
    unsigned int _i,_pngSize;
    char _welcome[] = "Welcome_to_sdnisc_2018_By.Zero";
 
	
    _dat_magic = ctf_read_file(ENCRYPT_PIC,16);
    _png_magic = ctf_read_file(NORMAL_PIC,16);

    for (_i = 0; _i < 16; _i++)
    {
        _key[_i] = _png_magic[_i] ^ (_dat_magic[_i] - 1) ^ 0x61 ^ _welcome[_i];
    }
    _key[16] = 0;
    printf("key: %s \n",_key);

    for (_i = 0; _i < 16; _i++)
    {
        _xorKey[_i] = _png_magic[_i] ^ (_dat_magic[_i] - 1) ^ 0x61;
    }
    // for ( _i = 0; _i < 16; _i++) printf("0x%02x ",_xorKey[_i]);
    
    _pngSize = ctf_get_file_size(ENCRYPT_PIC);
    _pngBuffer = ctf_read_file(ENCRYPT_PIC,_pngSize);
    if (_pngBuffer)
    {
        for ( _i = 0; _i < _pngSize; _i++)
        {
            _pngBuffer[_i] =  ( _pngBuffer[_i] -1) ^  _xorKey[_i % 16] ^ 0x61;
        }
        if(ctf_write_file(DECRYPT_PIC,_pngBuffer,_pngSize) == 1)
        {
            printf("write '%s' OK!\n ",DECRYPT_PIC);
        }else{
            printf("write '%s' FAILED!\n ",DECRYPT_PIC);
        }
        free(_pngBuffer);
    }else{
        printf("read '%s' FAILED!\n ",ENCRYPT_PIC);
    }

    free(_dat_magic);
    free(_png_magic);
    
}