I've got a buffer, in which i'm adding some plain text. I want to use openssl AES encryption to encrypt the text, then decrypt it, and print it back on the screen.
Code is running with no 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 of the fact that once placed in the new buffers, "encryptedbuffer" and "outbuffer", they are not null terminated "\0" , but even so, by printing out the raw data, i'm only getting rubbish after the decryption, At the end of the decryption, i'm assuming the \0 should also be decrypted and therefore the printf should print corectly.
Anyone knows how to make the decyption work?
Also any idea how to print the buffers using C++ libraries, maybe cout, and not printf?
Example: C program to encrypt and decrypt the string using RSA algorithm. RSA is another method for encrypting and decrypting the message. It involves public key and private key, where the public key is known to all and is used to encrypt the message whereas private key is only used to decrypt the encrypted message.
1 shows the block diagram of data encryption and decryption. In encryption process, encryption algorithm is applied to the original text, which transforms the original text into the encrypted or cipher text. During decryption process, decryption algorithm is applied to the encrypted text to get back the original text.
Decryption Approach:Find the length L of the string. Find the ceil and floor values of √Length and assign them to the variables. Create a 2D matrix and fill the matrix by characters of string column-wise. Read the matrix row-wise to get the decrypted string.
I notice a couple of possible issues:
key
as the previous call thus overwriting the key value. To make both calls up front like that, it would be necessary to use a separate key instance. Otherwise wait to call AES_set_decrypt_key
until after the encryption is done.AES_set_encrypt_key
needs to be 16 bytes long for the bit depth of 128. As it is, it will read 16 bytes, but the contents of those are undefined.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With