#include #include #include #include #include using namespace std; void hex_print(unsigned char* mes, int len) { for (int i = 0; i < len; ++i) cout << hex << (int)mes[i] << " "; cout << endl << endl; } int fileCrypt(unsigned char *key, int keyS, unsigned char iv[]) { ifstream in("NTL.zip", ifstream::binary); if (!in.is_open()) { cout << "Error opening in_file\n"; return 0; } in.seekg(0, ios::end); int plainS = in.tellg(); //cout << "Az allomany bajt merete: " << std::dec << plainS << endl; // a paddingolasi ertek meghatarozasa int trunc = plainS % BF_BLOCK; int cipherS = plainS + BF_BLOCK - trunc; cout << "paddingolt meret: " << cipherS << endl << endl; unsigned char *plaintext = new unsigned char[cipherS]; in.seekg(0, ios::beg); in.read((char*)plaintext, plainS); in.close(); //a nyilt szoveg paddingolasa if (trunc != 0) { for (int i = 0; i < BF_BLOCK - trunc; ++i) plaintext[plainS + i] = (BF_BLOCK - trunc) % BF_BLOCK; } unsigned char *ciphertext = new unsigned char[cipherS]; // titkositas BF_KEY enc_key; BF_set_key(&enc_key, keyS, key); BF_cbc_encrypt(plaintext, ciphertext, cipherS, &enc_key, iv, BF_ENCRYPT); ofstream out("crypt", ofstream::binary); if (!out.is_open()) { cout << "Error opening out_file\n"; return 1; } out.write((char*)ciphertext, cipherS); out.close(); } int fileDecrypt(unsigned char *key, int keyS, unsigned char ivD[]) { ifstream in1("crypt", ifstream::binary); if (!in1.is_open()) { cout << "Error opening in_file\n"; return 0; } in1.seekg(0, ios::end); int cipherS = in1.tellg(); //cout << "Az allomany bajt merete: " << std::dec << cipherS << endl; unsigned char *ciphertext = new unsigned char[cipherS]; in1.seekg(0, ios::beg); in1.read((char*)ciphertext, cipherS); in1.close(); //visszafejtes unsigned char *decryptedtext = new unsigned char[cipherS]; BF_KEY dec_key; BF_set_key(&dec_key, keyS, key); BF_cbc_encrypt (ciphertext, decryptedtext, cipherS, &dec_key, ivD, BF_DECRYPT); ofstream out1("ujNTL.zip", ofstream::binary); if (!out1.is_open()) { cout << "Error opening out_file\n"; return 1; } int plainS = cipherS - decryptedtext[cipherS - 1]; out1.write((char*)decryptedtext, plainS); out1.close(); return 0; } int main() { int keyS = 128; int temp = keyS / 8; // kulcs generalas unsigned char *key = new unsigned char[temp]; memset(key, 0, keyS / 8); if (!RAND_bytes(key, keyS / 8)) exit(-1); cout << "key:" << endl; hex_print(key, keyS/8); // init vektor generalas unsigned char iv[BF_BLOCK], ivD[BF_BLOCK]; RAND_bytes(iv, BF_BLOCK); memcpy(ivD, iv, BF_BLOCK); cout << "iv: " << endl; hex_print(iv, BF_BLOCK); fileCrypt(key, keyS, iv); fileDecrypt(key, keyS, ivD); return 0; }