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

时间:2014-01-30 00:00:40

标签: 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();

}

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

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

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

1 个答案:

答案 0 :(得分:3)

我注意到一些可能的问题:

  • 对AES_set_decrypt_key的调用使用与前一个调用相同的key,从而覆盖键值。要使这两个调用都像这样,需要使用单独的密钥实例。否则,请等待加密完成后再致电AES_set_decrypt_key
  • 传递给AES_set_encrypt_key的密钥缓冲区需要16字节长,位深度为128.实际上,它将读取16个字节,但这些内容未定义。