Crypto++ : CFB_Mode_ExternalCipher not working - c++

This is how the code look likes. Is there anything wrong with this.
The recover text does not match.
AES::Encryption aes1(key, key.size());
CFB_Mode_ExternalCipher::Encryption cfbEncryption(aes1, iv);
AES::Decryption aes2(key, key.size());
CFB_Mode_ExternalCipher::Decryption cfbDecryption(aes2, iv);
ArraySink cipherSink(cipher, data_size);
ArraySource ss1(plain, data_size, true, new StreamTransformationFilter(cfbEncryption, new Redirector(cipherSink)));
ArraySink recoverSink(recover, data_size);
ArraySource ss2(cipher, data_size, true, new StreamTransformationFilter(cfbDecryption, new Redirector(recoverSink)));

When using CTR Mode External Cipher in transformation, encryption is used for decryption as well.
https://www.codeproject.com/Articles/21877/Applied-Crypto-Block-Ciphers

Related

First 16 bytes of AES-128 CFB-8 decryption are damaged

I've been working on a project recently that should connect to a server with the help of a protocol. So far so good, but when I combed to decrypt the packages, I quickly noticed that something is not working properly.
The first 16 bytes of all packets are decrypted incorrectly. I have tried it with different libraries but that does not work either. I work in the C++ language and have so far used Crypto++ and OpenSSL for decryption, without success.
Under this Link you can find the protocol, here the decryption protocol Link and here is my corresponding code:
OpenSSL:
void init() {
unsigned char* sharedSecret = new unsigned char[AES_BLOCK_SIZE];
std::generate(sharedSecret,
sharedSecret + AES_BLOCK_SIZE,
std::bind(&RandomGenerator::GetInt, &m_RNG, 0, 255));
for (int i = 0; i < 16; i++) {
sharedSecretKey += sharedSecret[i];
}
// Initialize AES encryption and decryption
if (!(m_EncryptCTX = EVP_CIPHER_CTX_new()))
std::cout << "123" << std::endl;
if (!(EVP_EncryptInit_ex(m_EncryptCTX, EVP_aes_128_cfb8(), nullptr, (unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str())))
std::cout << "123" << std::endl;
if (!(m_DecryptCTX = EVP_CIPHER_CTX_new()))
std::cout << "123" << std::endl;
if (!(EVP_DecryptInit_ex(m_DecryptCTX, EVP_aes_128_cfb8(), nullptr, (unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str())))
std::cout << "123" << std::endl;
m_BlockSize = EVP_CIPHER_block_size(EVP_aes_128_cfb8());
}
std::string result;
int size = 0;
result.resize(1000);
EVP_DecryptUpdate(m_DecryptCTX, &((unsigned char*)result.c_str())[0], &size, &sendString[0], data.size());
Crypto++:
CryptoPP::CFB_Mode<CryptoPP::AES>::Decryption AESDecryptor((byte*)sharedSecret.c_str(), (unsigned int)16, sharedSecret.c_str(), 1);
std::string sTarget("");
CryptoPP::StringSource ss(data, true, new CryptoPP::StreamTransformationFilter(AESDecryptor, new CryptoPP::StringSink(sTarget)));
I think important to mention is that I use one and the same shared secret for the key and the iv (initialization vector). In other posts, this was often labeled as a problem. I do not know how to fix it in this case because the protocol want it.
I would be looking forward to a constructive feedback.
EVP_EncryptInit_ex(m_EncryptCTX, EVP_aes_128_cfb8(), nullptr,
(unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str()))
And:
CFB_Mode<AES>::Decryption AESDecryptor((byte*)sharedSecret.c_str(),
(unsigned int)16, sharedSecret.c_str(), 1);
std::string sTarget("");
StringSource ss(data, true, new StreamTransformationFilter(AESDecryptor, new StringSink(sTarget)));
It is not readily apparent, but you need to set feedback size for the mode of operation of the block cipher in Crypto++. The Crypto++ feedback size is 128 by default.
The code to set the feedback size of CFB mode can be found at CFB Mode on the Crypto++ wiki. You want the 3rd or 4th example down the page.
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(iv));
That is kind of an awkward way to pass parameters. It is documented in the sources files and on the wiki at NameValuePairs. It allows you to pass arbitrary parameters through consistent interfaces. It is powerful once you acquire a taste for it.
And then use params to key the encryptor and decryptor:
CFB_Mode< AES >::Encryption enc;
enc.SetKey( key, key.size(), params );
// CFB mode must not use padding. Specifying
// a scheme will result in an exception
StringSource ss1( plain, true,
new StreamTransformationFilter( enc,
new StringSink( cipher )
) // StreamTransformationFilter
); // StringSource
I believe your calls would look something like this (if I am parsing the OpenSSL correctly):
const byte* ptr = reinterpret_cast<const byte*>(sharedSecret.c_str());
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(ptr, 16));
CFB_Mode< AES >::Encryption enc;
enc.SetKey( ptr, 16, params );
In your production code you should use unique key and iv. So do something like this using HKDF:
std::string seed(AES_BLOCK_SIZE, '0');
std::generate(seed, seed + AES_BLOCK_SIZE,
std::bind(&RandomGenerator::GetInt, &m_RNG, 0, 255));
SecByteBlock sharedSecret(32);
const byte usage[] = "Key and IV v1";
HKDF<SHA256> hkdf;
hkdf.DeriveKey(sharedSecret, 32, &seed[0], 16, usage, COUNTOF(usage), nullptr, 0);
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(sharedSecret+16, 16));
CFB_Mode< AES >::Encryption enc;
enc.SetKey(sharedSecret+0, 0, params);
In the code above, sharedSecret is twice as large as it needs to be. You derive the key and iv from the seed using HDKF. sharedSecret+0 is the 16-byte key, and sharedSecret+16 is the 16-byte iv.

Properly Decrypt AES in GCM mode in Crypto++

I've been trying to encrypt and decrypt a file using AES in GCM mode using Crypto++. What this code is supposed to do is, given a password, hash it using PBKDF2< HMAC< SHA256>>, then encrypt and decrypt a file using the password hash as the key. After searching all over on Stack Overflow I've gotten this far:
using namespace Cryptopp;
const std::string password = "password";
const int iterations = 1000000;
const std::string fileName = "test.txt";
SecByteBlock derived(32);
SecByteBlock salt(16);
const int TAG_SIZE = AES::BLOCKSIZE;
AutoSeededRandomPool rng;
rng.GenerateBlock(salt, 16);
// KDF function
PKCS5_PBKDF2_HMAC<SHA256> kdf;
kdf.DeriveKey(
derived.data(),
derived.size(),
0,
(byte*)password.data(),
password.size(),
salt.data(),
salt.size(),
iterations);
// Key the cipher
GCM<AES>::Encryption encryptor;
encryptor.SetKeyWithIV(derived.data(), 16, derived.data() + 16, 16);
FileSource(fileName.c_str(), true,
new AuthenticatedEncryptionFilter(encryptor,
new FileSink(fileName.c_str()), false, TAG_SIZE));
// Key the cipher
GCM<AES>::Decryption decryptor;
decryptor.SetKeyWithIV(derived.data(), 16, derived.data() + 16, 16);
AuthenticatedDecryptionFilter decryptionFilter(decryptor,
new FileSink(fileName.c_str()), 16, TAG_SIZE);
FileSource(fileName.c_str(), true, new Redirector(decryptionFilter));
If the use of half of the derived hash from PBKDF2 as the key and half as the IV seems weird, this code is largely copied from How to use a custom key in Crypto++. Is this good practice in cryptography? Or should I generate a separate IV every time I encrypt?
Crypto++ throws a HashVerificationFailed exception, meaning the data was changed since encryption. So obviously I'm doing something wrong. What's wrong with my code?

Decrypted image is not same as original image

I just started working on cryptopp library. I have a image buffer and i want to encrypt with some key and then decrypt later but facing issue, decrypted and original images are not same.
I am not sure weather issue in encryption or not could some one help me out of this.
using qt creator
Code:
AutoSeededRandomPool prng;
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
prng.GenerateBlock( key, key.size() );
byte ctr[ AES::BLOCKSIZE ];
prng.GenerateBlock( ctr, sizeof(ctr) );
string cipher, encoded, recovered;
QFile file("original.png");
if(!file.open(QIODevice::ReadOnly)){
cout << "could not open the file"<< endl;
}
QByteArray buffer = file.readAll();
qDebug()<<"buffer length"<<buffer.length();
file.close();
try
{
CTR_Mode< AES >::Encryption e;
e.SetKeyWithIV( (byte*)key.data(), key.size(), ctr );
StringSource ss1( buffer, true,
new StreamTransformationFilter( e,
new StringSink( cipher )
)
);
}
catch( CryptoPP::Exception& e )
{
cerr << e.what() << endl;
exit(1);
}
qDebug()<<"cipher length "<<cipher.length();
try
{
CTR_Mode< AES >::Decryption d;
d.SetKeyWithIV( (byte*)key.data(), key.size(), ctr );
StringSource ss3( cipher, true,
new StreamTransformationFilter( d,
new StringSink( recovered )
)
);
}
catch( CryptoPP::Exception& e )
{
cerr << e.what() << endl;
exit(1);
}
qDebug()<<"recovered length "<<recovered.length();
QFile ouput("recovered.png");
if(ouput.open(QIODevice::WriteOnly)){
ouput.write(recovered.data(), recovered.size());
ouput.close();
}
response:
buffer length 538770
cipher length 8
recovered length 8
why my cipher length is 8 only.
QFile ouput("recovered.png");
if(ouput.open(QIODevice::WriteOnly)){
ouput.write(recovered.c_str());
ouput.close();
}
Let me throw mine in the pot.... You are treating binary data as a C-String, which means reading/writing stops at the first NULL character. You should use an overload that takes a pointer and size. Maybe something like:
ouput.write(recovered.data(), recovered.size());
(After code edits)
QByteArray buffer = file.readAll();
...
StringSource ss1( buffer, true, ...);
That's probably not producing expected results. Maybe you should try:
QByteArray buffer = file.readAll();
...
StringSource ss1( buffer.data(), buffer.size(), true, ...);
The above StringSource overload, with a pointer and size, is the one you should prefer in this case. Its the exact case it was designed for, and it saves the extra copy of buffer.
You could even use a FileSource and FileSink` to integrate with Crypto++::
FileSource ifile("original.png", true,
new StreamTransformationFilter(e,
new StringSink( cipher )
)
);
Also, Barmak is correct about:
In your case you call it ctr but it seems to be uninitialized...
Though it is uninitialized, the same [unknown] value is used for encryption and decryption, so the problem did not show its head. It will show up later, like when you encrypt on one machine and decrypt on another.
You should follow Barmak advice an initialize it. Maybe something like:
byte ctr[16];
OS_GenerateRandomBlock(false, ctr, sizeof(ctr));
OS_GenerateRandomBlock is discussed on Crypto++ wiki at RandomNumberGenerator.
You can usually send the counter in the plaintext with the message because its usually considered a public value. But it really depends on your security model.
Be sure to never reuse a security context in counter mode. Each message must be encrypted under a unique security context. The security context is the {key,ctr} pair.
You can also print the counter with:
byte ctr[16];
OS_GenerateRandomBlock(false, ctr, sizeof(ctr));
HexEncoder encoder(new FileSink(cout));
cout << "Counter: ";
encoder.Put(ctr, sizeof(ctr));
encoder.MessageEnd();
cout << endl;
The code above simply hex-encodes the raw byte array nd then prints it to stdout.
(comment) string key = "7D9BB722DA2DC8674E08C3D44AAE976F"; - You probably want a binary string; not an ASCII string. For Crypto++, see HexDecoder on the Crypto++ wiki. I'm not sure what QT offers for the service.
Since there's more space here... this is one of the things you could do:
string key, encodedKey = "7D9BB722DA2DC8674E08C3D44AAE976F";
StringSource ss(encodedKey, true, new HexDecoder(key));
After the statements execute, the string key will be binary data.
In your code you are converting the file content to Base64,
encrypting it, decrypting it and saving it to a file (thus saving a the png file as Base64)
You should encrypt the raw file data (and not the Base64 encoded one).
Edit: After your edit I don't know what fails. Please try the following function, which works for me. Uses FileSource and FileSink, but should work with StringSource and StringSink accordingly.
bool encryptdecrypt(const std::string& filename)
{
std::string key = "7D9BB722DA2DC8674E08C3D44AAE976F";
byte ctr[ CryptoPP::AES::BLOCKSIZE ];
std::string cipher;
try
{
CryptoPP::CTR_Mode< CryptoPP::AES >::Encryption e;
e.SetKeyWithIV( (byte*)key.data(), key.size(), ctr );
CryptoPP::FileSource( filename.c_str(), true,
new CryptoPP::StreamTransformationFilter( e,
new CryptoPP::StringSink( cipher )
)
);
}
catch( CryptoPP::Exception& e )
{
std::cerr << e.what() << std::endl;
return false;
}
try
{
CryptoPP::CTR_Mode< CryptoPP::AES >::Decryption d;
d.SetKeyWithIV( (byte*)key.data(), key.size(), ctr );
CryptoPP::StringSource( cipher, true,
new CryptoPP::StreamTransformationFilter( d,
new CryptoPP::FileSink( ( "decrypted_" + filename ).c_str() )
)
);
}
catch( CryptoPP::Exception& e )
{
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
I found the issue with QByteArray buffer. i just converted to std::string its working.
QByteArray buffer = file.readAll();
// string
std::string stdString(buffer.data(), buffer.length());
//used stdString instead of buffer in pipeline
StringSource ss1(stdString, true,
new StreamTransformationFilter( e,
new StringSink( cipher )
)
);

'message hash or MAC not valid' exception after decryption

I'm trying to make a program that encrypts files (.jpg and .avi) using the crypto++ libraries. My aim is to make a program that successfully encrypts video files using AES-256.
I did text examples of AES encryption from here and they ran successfully (meaning that the library is setup correctly). However, the following simple code produces the exception
HashVerificationFilter: message hash or MAC not valid
Code:
AutoSeededRandomPool prng;
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
prng.GenerateBlock(key, key.size());
SecByteBlock iv(AES::BLOCKSIZE);
prng.GenerateBlock(iv, iv.size());
string ofilename = "testimage.png";
string efilename;
string rfilename = "testimagerecovered.png";
try
{
GCM< AES >::Encryption e;
e.SetKeyWithIV(key, key.size(), iv, iv.size());
ifstream ofile(ofilename.c_str(), ios::binary);
ofile.seekg(0, ios_base::beg);
FileSource fs1(ofilename.c_str(), true,
new AuthenticatedEncryptionFilter(e,
new StringSink(efilename)));
GCM< AES >::Decryption d2;
d2.SetKeyWithIV(key, key.size(), iv, sizeof(iv));
StringSource fs2(efilename, true,
new AuthenticatedDecryptionFilter( d2,
new FileSink (rfilename.c_str()),
AuthenticatedDecryptionFilter::THROW_EXCEPTION));
}
catch(const Exception &e)
{
cerr << e.what() << endl;
exit(1);
}
return 0;
I suspect I am not implementing the AES algorithm correctly. However, I am unable to find a solution for the last two days. I'm using Eclipse Luna on Ubuntu 14.04.
PS I have gone through the following answers
How to read an image to a string for encrypting Crypto++
How to loop over Blowfish Crypto++
Please use iv.size() rather than sizeof(iv) when you try to set d2.SetKeyWithIV, just like what you have done to e.SetKeyWithIV.
Because in this program, the value of iv.size() is 16, but sizeof(iv) is 24. Then it will work.
GCM< AES >::Decryption d2;
d2.SetKeyWithIV(key, key.size(), iv, iv.size()); //here was a misuse of sizeof(iv)
StringSource fs2(efilename, true,
new AuthenticatedDecryptionFilter( d2,
new FileSink (rfilename.c_str()),
AuthenticatedDecryptionFilter::THROW_EXCEPTION));
The code which has passed my test is as above.

How to encrypt a byte array with Crypto++

How can I encrypt a byte array with Crypto++'s RSA implementation? I already found an example for strings. But I can't find a good example how to do the same for a byte array.
This is my first attempt:
//dataSize: Size of data that is going to be send
//dataToSend Bytes to send to the user
//seedPool is an AutoSeededRandomPool
CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor(publicKey);
int size = 64000;
byte * cipher = new byte(size);
CryptoPP::ArraySink* test = new CryptoPP::ArraySink(cipher, size);
CryptoPP::ArraySource as((byte*)dataToSend, dataSize, true, new CryptoPP::PK_EncryptorFilter(seedPool, encryptor, test));
int newDataSize = test->TotalPutLength();
unsigned int bytesSend = ::send(socketLink, (char *)(cipher), (int)newDataSize, 0);
delete[] cipher;
This doesn't work. TotalPutLength will always return 0 but there is data put in cipher.
What is a safe way to implement this? I don't want to be vulnerable for buffer overflows or any other attack.
byte * cipher = new byte(size);
I believe this should be:
byte * cipher = new byte[size];
Otherwise, I think you get one byte initialized to 6400 (which is truncated to 0x00).
CryptoPP::ArraySink * test = new CryptoPP::ArraySink(cipher, size);
This is kind of different. You can stay out of the memory manager if you'd like:
CryptoPP::ArraySink test(cipher, size);
int newDataSize = test->TotalPutLength();
I've never used TotalPutLength, and I did not see it documented on a BufferedTransformation or Sink. So I don't really have any advice on what its returning.
TotalPutLength is OK to use. An ArraySink could return the wrong value if the sink was full. It would happen if the array was fixed and too small for all the data. We cleared that issue at Crypto++ 5.6.3 or 5.6.4.
If you want to count the number of bytes processed (even if the sink cannot store they bytes), then you can also use a MeterFilter:
byte data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
string encoded;
MeterFilter meter( new StringSink( encoded ) );
ArraySource( data, sizeof( data ), true,
new HexEncoder(
new Redirector( meter ),
true /*UCase*/, 2 /*Group*/,
" " /*Separator*/
)
);
cout << "processed " << meter.GetTotalBytes() << " bytes" << endl;
cout << encoded << endl;
Output:
Processed 23 bytes
00 01 02 03 04 05 06 07
How can you encrypt a byte array with Cryptopp RSA implementation
Now we're talking ;) Try this from the Crypto++ wiki on RSA Encryption.
////////////////////////////////////////////////
// Generate keys
AutoSeededRandomPool rng;
InvertibleRSAFunction params;
params.GenerateRandomWithKeySize( rng, 1536 );
RSA::PrivateKey privateKey( params );
RSA::PublicKey publicKey( params );
string plain="RSA Encryption", cipher, recovered;
////////////////////////////////////////////////
// Encryption
RSAES_OAEP_SHA_Encryptor e( publicKey );
StringSource ss1( plain, true,
new PK_EncryptorFilter( rng, e,
new StringSink( cipher )
) // PK_EncryptorFilter
); // StringSource
////////////////////////////////////////////////
// Decryption
RSAES_OAEP_SHA_Decryptor d( privateKey );
StringSource ss2( cipher, true,
new PK_DecryptorFilter( rng, d,
new StringSink( recovered )
) // PK_DecryptorFilter
); // StringSource
assert( plain == recovered );