OpenSSL 使用 EVP 与算法 API 进行对称加密 [英] OpenSSL using EVP vs. algorithm API for symmetric crypto

查看:39
本文介绍了OpenSSL 使用 EVP 与算法 API 进行对称加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的 linux 机器上安装了 openssl 并浏览了头文件和文档(这是非常不够的 :().

Hi i have installed openssl on my linux machine and going through the header files and documentation (which is highly insufficint :( ).

我正在尝试构建一个使用对称加密算法的项目(在c"中)(我专注于 aes256cbc).问题是我对如何在我的代码中使用库函数感到困惑.

i am trying to build a project(in 'c') which uses symmetric crypto algos (i am focusing on aes256cbc). The problem is i am confused as in how to use the library functions in my code.

对于 aes256cbc 的实现,我可以直接使用aes.h"头文件中定义的函数(最初出现在我看来).

For my implementation of aes256cbc i can directly use the functions defined in the 'aes.h' header file(which appeared to me at the first place).

但在谷歌搜索时,我遇到了一些使用evp.h"函数来执行此操作的教程http://saju.net.in/code/misc/openssl_aes.c.txt

But on googling i came accross some tutorial for this which are using 'evp.h' functions to do this http://saju.net.in/code/misc/openssl_aes.c.txt

这个有什么具体原因还是直接访问aes.h函数比较好.

Is there a specific reason for this or directly accessing the aes.h functions is better.

此外,如果有人可以向我指出有关使用 openssl 加密库的任何类型的良好文档/教程,我将不胜感激.

非常感谢

P.S 原谅我幼稚

推荐答案

使用 EVP API 的优点是您可以以通用方式对 OpenSSL 支持的所有对称密码使用相同的 API.这使得替换所使用的算法变得更容易,或者使算法在稍后阶段可由用户配置.您编写的大部分代码并非特定于您选择的加密算法.

Using the EVP API has the advantage that you can use the same API for all the symmetric ciphers that OpenSSL supports, in a generic way. This makes it way easier to replace the algorithm used, or make the algorithm user-configurable at a later stage. Most of the code you write is not specific to the encryption algorithm you selected.

以下是在 CBC 模式下使用 AES-256 进行加密的简单示例:

Here's a simple example for encryption with AES-256 in CBC mode:

#include <stdio.h>
#include <openssl/evp.h>

int main()
{
    EVP_CIPHER_CTX ctx;
    unsigned char key[32] = {0};
    unsigned char iv[16] = {0};
    unsigned char in[16] = {0};
    unsigned char out[32]; /* at least one block longer than in[] */
    int outlen1, outlen2;

    EVP_EncryptInit(&ctx, EVP_aes_256_cbc(), key, iv);
    EVP_EncryptUpdate(&ctx, out, &outlen1, in, sizeof(in));
    EVP_EncryptFinal(&ctx, out + outlen1, &outlen2);

    printf("ciphertext length: %d
", outlen1 + outlen2);

    return 0;
}

为简单起见,我省略了错误处理.

For simplicity, I omitted error handling.

IMO 最重要的 OpenSSL 文档之一是 Viega/Messier/Chandra 的 OpenSSL 网络安全.它是从 2002 (0.9.7) 开始的,所以没有涵盖过去 10 年中 OpenSSL 的变化,但与仅使用手册页相比,IMO 仍然是学习 OpenSSL 的一种更轻松的方式.

IMO one of the most important pieces of documentation on OpenSSL is Network Security with OpenSSL by Viega/Messier/Chandra. It is from 2002 (0.9.7), so does not cover changes to OpenSSL during the last 10 years, but it is IMO still a less painful way to learn OpenSSL than by using only the manual pages.

这篇关于OpenSSL 使用 EVP 与算法 API 进行对称加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆