据我所见,openssl 中的 EVP 功能仅接受unsigned char *
作为输入。一个示例代码是:
int gcm_encrypt(unsigned char *plaintext, int plaintext_len,
unsigned char *aad, int aad_len,
unsigned char *key,
unsigned char *iv, int iv_len,
unsigned char *ciphertext,
unsigned char *tag)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new()))
handleErrors();
/* Initialise the encryption operation. */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
handleErrors();
/*
* Set IV length if default 12 bytes (96 bits) is not appropriate
*/
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL))
handleErrors();
/* Initialise key and IV */
if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
handleErrors();
/*
* Provide any AAD data. This can be called zero or more times as
* required
*/
if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
/*
* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
/*
* Finalise the encryption. Normally ciphertext bytes may be written at
* this stage, but this does not occur in GCM mode
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
handleErrors();
ciphertext_len += len;
/* Get the tag */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
handleErrors();
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
我想打开/读取任何类型的文件并将其用作纯文本来加密它。这样的代码如何使我能够读取任何类型的文件?
尝试时,我总是以初始化错误告终:
FILE * pFile;
long lSize;
char * buffer; // same error when using: unsigned char * buffer;
size_t result;
pFile = fopen ( "test.txt" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
cout << typeid(buffer).name() << endl;
unsigned char plaintext[] = buffer; <- Array initializer must be an initializer list or string literal
是否还有其他库也支持 aead 或 openssl funktion 更足以完成此任务?
我得到的错误信息是:
evp-encrypt_input_file.cpp:43:16: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
~~~~~~~^~~~~~~~
evp-encrypt_input_file.cpp:48:19: error: initializer fails to determine size of ‘plaintext’
unsigned char plaintext[] = buffer;
^~~~~~~~~
evp-encrypt_input_file.cpp:48:33: error: array must be initialized with a brace-enclosed initializer
unsigned char plaintext[] = buffer;
另外代码必须是c++,不能使用c。