Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * AESDemoClass.cpp
- *
- * Created on: Sep 13, 2019
- * Author: yulia
- */
- #include <iostream>
- #include <fstream>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <vector>
- #include <openssl/aes.h>
- #include "AESDemoClass.h"
- using namespace std;
- AESDemoClass::AESDemoClass() {
- }
- AESDemoClass::~AESDemoClass() {
- }
- /* AES key for Encryption and Decryption */
- const static unsigned char aes_key[]={0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};
- void AESDemoClass::aesDemo(){
- /* Input data to encrypt */
- vector<char> input = readAllBytes("input.txt");
- int n = input.size();
- unsigned char aes_input[n];
- for (int i = 0; i < n; i++)
- aes_input[i] = input[i];
- // unsigned char aes_input[n] = arr;
- /* Init vector */
- unsigned char iv[AES_BLOCK_SIZE];
- memset(iv, 0x00, AES_BLOCK_SIZE);
- /* Buffers for Encryption and Decryption */
- unsigned char enc_out[sizeof(aes_input)];
- unsigned char dec_out[sizeof(aes_input)];
- /* AES-128 bit CBC Encryption */
- AES_KEY enc_key, dec_key;
- AES_set_encrypt_key(aes_key, sizeof(aes_key)*8, &enc_key);
- AES_cbc_encrypt(aes_input, enc_out, sizeof(aes_input), &enc_key, iv, AES_ENCRYPT);
- /* AES-128 bit CBC Decryption */
- memset(iv, 0x00, AES_BLOCK_SIZE); // don't forget to set iv vector again, else you can't decrypt data properly
- AES_set_decrypt_key(aes_key, sizeof(aes_key)*8, &dec_key); // Size of key is in bits
- AES_cbc_encrypt(enc_out, dec_out, sizeof(aes_input), &dec_key, iv, AES_DECRYPT);
- /* Printing and Verifying */
- print_data("\n Original ",aes_input, sizeof(aes_input)); // you can not print data as a string, because after Encryption its not ASCII
- print_data("\n Encrypted",enc_out, sizeof(enc_out));
- print_data("\n Decrypted",dec_out, sizeof(dec_out));
- }
- void AESDemoClass::print_data(const char *title, const void* data, int len)
- {
- printf("%s : ",title);
- const unsigned char * p = (const unsigned char*)data;
- int i = 0;
- for (; i<len; ++i)
- printf("%02X ", *p++);
- printf("\n");
- }
- std::vector<char> AESDemoClass::readAllBytes(char const* filename){
- ifstream ifs(filename, ios::binary|ios::ate);
- ifstream::pos_type pos = ifs.tellg();
- std::vector<char> input(pos);
- ifs.seekg(0, ios::beg);
- ifs.read(&input[0], pos);
- return input;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement