Encryption and decryption using C ++

I have a buffer in which I add plain text. I want to use AES encryption for opensl to encrypt text, then decrypt it and print it on the screen.

The code works without errors.

#include <fstream> #include <iostream> #include <stdio.h> #include <string> #include <openssl/aes.h> using namespace std; void main() { // Buffers unsigned char inbuffer[1024]; unsigned char encryptedbuffer[1024]; unsigned char outbuffer[1024]; // CODE FOR ENCRYPTION //-------------------- unsigned char oneKey[] = "abc"; AES_KEY key; AES_set_encrypt_key(oneKey,128,&key); AES_set_decrypt_key(oneKey,128,&key); //-------------------- string straa("hello world\n"); memcpy((char*)inbuffer,straa.c_str(),13); printf("%s",inbuffer); //this prints out fine AES_encrypt(inbuffer,encryptedbuffer,&key); //printf("%s",encryptedbuffer); //this is expected to pring out rubbish, so is commented AES_decrypt(encryptedbuffer,outbuffer,&key); printf("%s",outbuffer); //this is not pringint "hello world" getchar(); } 

I am aware that after placing "encryptedbuffer" and "outbuffer" in the new buffers, they do not end with zero "\ 0", but even so, when printing raw data, I only received garbage after decryption. At the end of decryption, I assume that \ 0 must also be decrypted, and therefore printf must print correctly.

Does anyone know how to make decite work?

Also any idea how to print buffers using C ++ libraries, possibly cout, not printf?

+6
source share
1 answer

I notice a couple of possible problems:

  • The AES_set_decrypt_key call uses the same key as the previous call, thus overwriting the key value. To make both calls ahead, you would need to use a separate key instance. Otherwise, wait until AES_set_decrypt_key until encryption is complete.
  • The key buffer passed to AES_set_encrypt_key must be 16 bits long for a bit depth of 128. Be that as it may, it will read 16 bytes, but their contents are undefined.
+3
source

All Articles