I'm using 'aes-128-ctr' algorithm to crypt and decrypt strings with nodejs. I would like to use the same algorithm in c++. I know that cryptopp library implements this algorithm. However I don't know how to use it. I'm looking for an equivalent c++ implementation to the following node js code :
var crypto = require('crypto'),
algorithm = 'aes-128-ctr',
password = 'DE575AE3F34F8';
function encrypt(text){
var cipher = crypto.createCipher(algorithm,password);
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
This is what I found in c++ :
#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <sstream>
#include "cryptopp/modes.h"
#include "cryptopp/aes.h"
#include "cryptopp/filters.h"
#include "aes.hpp"
using CryptoPP::AES;
unsigned char key [16] = "DE575AE3F34F8"; /*!< Key */
unsigned char iv [16] = "7172737475767";
/*!
Function du encrypt data in url
*/
std::string crytAES (std::string chain) {
/*!
AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-bit).
This key is secretly exchanged between two parties before communication begins.
DEFAULT_KEYLENGTH= 16 bytes
*/
/*byte iv [AES::BLOCKSIZE];*/
memset( key, 0x00, AES::DEFAULT_KEYLENGTH);
memset( iv, 0x00, AES::BLOCKSIZE );
//!String
std::string urlBeforeEncrypt = chain;
std::string ciphertext;
//!Encrypt
AES::Encryption aesEncryption(key,16 );
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( urlBeforeEncrypt.c_str() ), urlBeforeEncrypt.length() + 1 );
stfEncryptor.MessageEnd();
string concat = "";
for( int i = 0; i < ciphertext.size(); i++ ) {
std::stringstream sstm;
sstm << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
string ans = sstm.str();
concat += ans;
}
return concat;
}
for this string : Attack at dawn!! The c++ code outputs the following encryption : 0x5 0xe1 0x72 0x60 0x76 0xb5 0xe9 0x33 0x6a 0x69 0x9d 0xba 0x5e 0x55 0x98 0x49 0xd6 0xb 0xd0 0xd0 0xfb 0x9f 0x8f 0xd2 0x72 0x26 0x68 0x5a 0xf7 0x8b 0x28
While the node js code outputs the followinf encryption : 148e6bf91715d1f96de84c6880a356de
Thank you for your answer !!
Aucun commentaire:
Enregistrer un commentaire