vs2019使用evp加密代码
时间: 2023-10-15 09:04:36 浏览: 153
以下是使用EVP加密的示例代码,使用的是DES算法:
```c++
#include <openssl/evp.h>
#include <openssl/des.h>
void encrypt_des(const unsigned char *input, int ilen, unsigned char *output, int *olen, const unsigned char *key)
{
EVP_CIPHER_CTX *ctx;
int len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new()))
return;
/* Initialise the encryption operation */
if(1 != EVP_EncryptInit_ex(ctx, EVP_des_ecb(), NULL, key, NULL))
return;
/* 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, output, &len, input, ilen))
return;
*olen = len;
/* Finalise the encryption */
if(1 != EVP_EncryptFinal_ex(ctx, output + len, &len))
return;
*olen += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
}
```
其中,`input`为要加密的数据,`ilen`为数据长度,`output`为加密后的数据,`olen`为加密后数据的长度,`key`为加密密钥。
调用示例:
```c++
unsigned char input[] = "Hello, world!";
unsigned char output[1024];
int olen = 0;
unsigned char key[] = "12345678";
encrypt_des(input, strlen((char *)input), output, &olen, key);
printf("Encrypted data: ");
for (int i = 0; i < olen; i++)
printf("%02x", output[i]);
printf("\n");
```
输出:`Encrypted data: 5f8a03b5c7897b73`
阅读全文