使用C++进行加密和解密

Dan*_*rar 6 c++ openssl aes encryption-symmetric

我有一个缓冲区,我正在添加一些纯文本.我想使用openssl AES加密来加密文本,然后将其解密,然后将其打印回屏幕.

代码正在运行,没有错误.

#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string>
#include <openssl/aes.h>
using namespace std;

void main()
{

// Buffers
unsigned char inbuffer[1024];
unsigned char encryptedbuffer[1024];
unsigned char outbuffer[1024];


// CODE FOR ENCRYPTION
//--------------------
unsigned char oneKey[] = "abc";
AES_KEY key; 

AES_set_encrypt_key(oneKey,128,&key);
AES_set_decrypt_key(oneKey,128,&key);

//--------------------


string straa("hello world\n");
memcpy((char*)inbuffer,straa.c_str(),13);


printf("%s",inbuffer);
//this prints out fine

AES_encrypt(inbuffer,encryptedbuffer,&key);
//printf("%s",encryptedbuffer);
//this is expected to pring out rubbish, so is commented

AES_decrypt(encryptedbuffer,outbuffer,&key);
printf("%s",outbuffer);
//this is not pringint "hello world"

getchar();

}
Run Code Online (Sandbox Code Playgroud)

我知道一旦放入新缓冲区"encryptedbuffer"和"outbuffer",它们不会以空终止"\ 0",但即便如此,通过打印出原始数据,我只是在垃圾后解密,在解密结束时,我假设\ 0也应该被解密,因此printf应该打印corectly.

任何人都知道如何使decyption工作?

还有任何想法如何使用C++库打印缓冲区,也许是cout,而不是printf?

Mar*_*ins 3

我注意到几个可能的问题:

  • 对 AES_set_decrypt_key 的调用key与之前的调用相同,因此会覆盖密钥值。要像这样预先进行这两个调用,需要使用单独的密钥实例。否则请等待AES_set_decrypt_key加密完成后再调用。
  • 对于 128 位深度,传递给的密钥缓冲区AES_set_encrypt_key需要 16 个字节长。实际上,它将读取 16 个字节,但这些内容未定义。

  • @DaniMarianMorar 留意马克的警告。您的密钥*必须*为 16 字节宽。如果不是,OpenSSL 库将盲目地访问密钥后面的内存中的任何内容,这是**未定义的行为**。想象一下,如果接下来的事情是你的密文块,会产生什么令人讨厌的后果。 (2认同)