Skip to content

Instantly share code, notes, and snippets.

@melvyniandrag
Created November 7, 2017 17:16
Show Gist options
  • Save melvyniandrag/f38552c70c49227f140c7e1cdbb427e0 to your computer and use it in GitHub Desktop.
Save melvyniandrag/f38552c70c49227f140c7e1cdbb427e0 to your computer and use it in GitHub Desktop.
aes 256 in grypt
#include <cassert>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <gcrypt.h>
#include <string>
void closeHandle( gcry_cipher_hd_t &handle )
{
gcry_cipher_close( handle );
}
char _s_gKey[32]{
'1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6',
'1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6'
};
void printCharsAsHex( const char* charArr, const int encryptedSize )
{
std::stringstream ss;
for(int i = 0; i < encryptedSize; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << int(charArr[i]) << " ";
}
ss << "\n";
std::cout << "*****************EncryptedData********************" << std::endl;
std::cout << ss.str() << std::endl;
std::cout << "**************************************************" << std::endl;
}
void openHandle( gcry_cipher_hd_t &handle, uint32_t &blkLength )
{
gcry_error_t err = GPG_ERR_NO_ERROR;
const gcry_cipher_algos MyCipher = GCRY_CIPHER_AES256;
const uint32_t KeyLength = gcry_cipher_get_algo_keylen( MyCipher );
assert( KeyLength == 32 );
blkLength = gcry_cipher_get_algo_blklen( MyCipher );
static bool s_isCipherInitialized = false;
if ( s_isCipherInitialized == false )
{
static_cast<void>( gcry_control( GCRYCTL_ANY_INITIALIZATION_P ) );
static_cast<void>( gcry_control( GCRYCTL_DISABLE_SECMEM, 0 ) );
static_cast<void>( gcry_control( GCRYCTL_INITIALIZATION_FINISHED ) );
s_isCipherInitialized = true;
}
err = gcry_cipher_open( &handle, MyCipher, GCRY_CIPHER_MODE_CFB, 0 );
err = gcry_cipher_setkey( handle, _s_gKey, KeyLength );
}
int main(int argc, char** argv){
uint32_t data_ptr_buf_len = 32;
char data[data_ptr_buf_len + 1]{'a','b','c','d','e','f','g','h','a','b','c','d','e','f','g','h', '\0'};
std::cout << "**************** Original Data*******************" << std::endl;
std::cout << data << std::endl;
std::cout << "*************************************************" << std::endl;
gcry_cipher_hd_t handle;
memset(&handle, 0, sizeof(handle));
uint32_t blkLength = 0;
openHandle( handle, blkLength );
gcry_error_t err = GPG_ERR_NO_ERROR;
err = gcry_cipher_encrypt(handle, data, data_ptr_buf_len, NULL, 0);
closeHandle(handle);
printCharsAsHex( data, data_ptr_buf_len );
openHandle(handle, blkLength);
err = gcry_cipher_decrypt(handle, data, data_ptr_buf_len, NULL, 0);
closeHandle(handle);
std::string s(data);
std::cout << "*************** Decrypted Data *******************" << std::endl;
std::cout << s << std::endl;
std::cout << "**************************************************" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment