解密AES-256加密文件无法正常工作

时间:2022-12-29 13:13:25

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

我使用Botan库进行加密,我的加密代码如下所示。

  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.

同样的上述生成的解密密钥和InitializationVector iv用于解密。

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

解密会引发异常AES-256 / EAX:消息验证失败

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

我在这里做错了什么以及如何正确解密上面的加密文件。

1 个解决方案

#1


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.

问题是ifstream和ofstream假设字符输出。如果你通过使用std :: ios :: binary作为第二个参数来配置它来处理二进制文件,那么你的代码应该没问题。如果它也没有明确编码密文,则Botan API参考也会使用它。

#1


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.

问题是ifstream和ofstream假设字符输出。如果你通过使用std :: ios :: binary作为第二个参数来配置它来处理二进制文件,那么你的代码应该没问题。如果它也没有明确编码密文,则Botan API参考也会使用它。