danial weaber
danial weaber

Reputation: 876

decrypting a AES-256 encrypted file not working

I use the Botan library for encrypting and my encrypting code looks like below.

  LibraryInitializer init;
  AutoSeeded_RNG rng;
  string passphrase="mypassword";


  PBKDF* pbkdf = get_pbkdf("PBKDF2(SHA-256)");
  SecureVector<byte> salt = rng.random_vec(16);
  InitializationVector iv(rng,16);
  OctetString aes256_key = pbkdf->derive_key(32, passphrase,&salt[0],   salt.size(), 10000 );
  cout<<"Encryption key : " << aes256_key.as_string() <<endl ;


 ifstream infile ("readme.txt");
 ofstream outfile ("encrypt.txt");



Pipe pipe(get_cipher("AES-256/EAX", aes256_key,iv, ENCRYPTION) );


pipe.start_msg();
infile>>pipe;
pipe.end_msg();

SecureVector<byte> cl = pipe.read_all();

outfile.write((const char*)cl.begin(), cl.size());


outfile.flush();
outfile.close();
infile.close();

this code looks working great and encrypt the input file. i posted this code to determine if there is an error in the encryption. (but I assume that the encryption is done correctly)

now the above encrypted file is tried to decrypt by the following code.

ifstream infile2 ("encrypt.txt");
ofstream outfile2 ("decrypt.txt");




Pipe pipe2 (get_cipher("AES-256/EAX", aes256_key, iv, DECRYPTION) );


pipe2.start_msg();
infile2 >> pipe2;
pipe2.end_msg();

SecureVector<byte> cl2 = pipe2.read_all();

outfile2.write((const char*)cl2.begin(), cl2.size());

outfile2.close();
infile2.close();
}

the same above generated decryption key and the InitializationVector iv is used for the decryption.

the decryption throws an exception AES-256/EAX : message authentication failed

what am I doing wrong here and how to decrypt the above encryptrd file correctly.

Upvotes: 2

Views: 758

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94058

The problem is that ifstream and ofstream assumes character output. If you configure it to handle binary by using std::ios::binary as second argument then your code should be alright. This is also used by the Botan API reference if it doesn't explicitly encode the ciphertext as well.

Upvotes: 3

Related Questions