C语言 如何在OpenSSL中使用AES进行加密

y1aodyip  于 2023-05-16  发布在  其他
关注(0)|答案(4)|浏览(247)

我试图写一个示例程序来做AES加密使用OpenSSL。我试着浏览OpenSSL文档(这是一个痛苦),不能弄清楚太多。我浏览了代码,找到了API的使用,我写了一个小程序如下(请省略行号)。我没有看到任何加密发生……我错过了什么吗?
PS:我在编译时没有任何错误。

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

static const unsigned char key[] = {
  0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
  0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};

void main()
{
    unsigned char text[]="virident";
    unsigned char out[10]; 
    unsigned char decout[10];

    AES_KEY wctx;

    AES_set_encrypt_key(key, 128, &wctx);
    AES_encrypt(text, out, &wctx);  

    printf("encryp data = %s\n", out);
   
    AES_decrypt(out, decout, &wctx);
    printf(" Decrypted o/p: %s \n", decout);
}

请帮我弄清楚这一点…

eqoofvh9

eqoofvh91#

查看此链接,它有一个使用EVP API使用AES 256 CBC加密/解密数据的示例代码。
https://github.com/saju/misc/blob/master/misc/openssl_aes.c
您还可以在我在https://github.com/llubu/mpro开发的一个详细的开源项目中查看AES 256 CBC的使用情况
代码是足够详细的注解,如果你仍然需要更多的解释API本身,我建议看看这本书*网络安全与OpenSSL的Viega/Messier/钱德拉***(谷歌它,你会很容易地找到一个PDF的这..)阅读第6章,这是特定于对称密码使用EVP API..这实际上帮助我理解了使用EVP的各种功能和结构背后的原因。
如果你想深入了解OpenSSL加密库,我建议你从
openssl网站**(你机器上安装的版本)下载代码,然后查看EVP和aeh API的实现。
从你上面发布的代码中还有一个建议,我看到你正在使用aes.h的API,而不是使用EVP。看看这样做的原因在这里OpenSSL using EVP vs. algorithm API for symmetric crypto很好地解释了丹尼尔在一个问题问我。

0dxa2lsx

0dxa2lsx2#

我试图写一个示例程序来做AES加密使用OpenSSL。
这个答案很受欢迎,所以我将提供一些最新的东西,因为OpenSSL添加了一些可能会帮助您的操作模式。
首先,不要使用AES_encryptAES_decrypt。它们的级别很低,很难使用。此外,它是一个纯软件例程,它永远不会使用硬件加速,如AES-NI。最后,它在一些不知名的平台上会遇到字节序问题。
使用EVP_*接口。EVP_*函数使用硬件加速,如AES-NI(如果可用)。而且它不会在晦涩的平台上遇到endianess问题。
第二,您可以使用像CBC这样的模式,但密文将缺乏完整性和真实性保证。因此,您通常需要EAX、CCM或GCM等模式。(或者您必须在加密后使用单独的密钥手动应用HMAC。
第三,OpenSSL有一个wiki页面,你可能会感兴趣:EVP Authenticated Encryption and Decryption,使用GCM模式。
最后,这里是使用AES/GCM加密的程序。OpenSSL wiki示例就是基于它。

#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <string.h>   

int main(int arc, char *argv[])
{
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();     

    /* Set up the key and iv. Do I need to say to not hard code these in a real application? :-) */

    /* A 256 bit key */
    static const unsigned char key[] = "01234567890123456789012345678901";

    /* A 128 bit IV */
    static const unsigned char iv[] = "0123456789012345";

    /* Message to be encrypted */
    unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";

    /* Some additional data to be authenticated */
    static const unsigned char aad[] = "Some AAD data";

    /* Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, dependant on the
     * algorithm and mode
     */
    unsigned char ciphertext[128];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[128];

    /* Buffer for the tag */
    unsigned char tag[16];

    int decryptedtext_len = 0, ciphertext_len = 0;

    /* Encrypt the plaintext */
    ciphertext_len = encrypt(plaintext, strlen(plaintext), aad, strlen(aad), key, iv, ciphertext, tag);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext is:\n");
    BIO_dump_fp(stdout, ciphertext, ciphertext_len);
    printf("Tag is:\n");
    BIO_dump_fp(stdout, tag, 14);

    /* Mess with stuff */
    /* ciphertext[0] ^= 1; */
    /* tag[0] ^= 1; */

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, aad, strlen(aad), tag, key, iv, decryptedtext);

    if(decryptedtext_len < 0)
    {
        /* Verify error */
        printf("Decrypted text failed to verify\n");
    }
    else
    {
        /* Add a NULL terminator. We are expecting printable text */
        decryptedtext[decryptedtext_len] = '\0';

        /* Show the decrypted text */
        printf("Decrypted text is:\n");
        printf("%s\n", decryptedtext);
    }

    /* Remove error strings */
    ERR_free_strings();

    return 0;
}

void handleErrors(void)
{
    unsigned long errCode;

    printf("An error occurred\n");
    while(errCode = ERR_get_error())
    {
        char *err = ERR_error_string(errCode, NULL);
        printf("%s\n", err);
    }
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad,
            int aad_len, unsigned char *key, unsigned char *iv,
            unsigned char *ciphertext, unsigned char *tag)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, ciphertext_len = 0;

    /* 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, 16, 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(aad && aad_len > 0)
    {
        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(plaintext)
    {
        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;
}

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
            int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
            unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, plaintext_len = 0, ret;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the decryption operation. */
    if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    if(aad && aad_len > 0)
    {
        if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
            handleErrors();
    }

    /* Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary
     */
    if(ciphertext)
    {
        if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
            handleErrors();

        plaintext_len = len;
    }

    /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
        handleErrors();

    /* Finalise the decryption. A positive return value indicates success,
     * anything else is a failure - the plaintext is not trustworthy.
     */
    ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    if(ret > 0)
    {
        /* Success */
        plaintext_len += len;
        return plaintext_len;
    }
    else
    {
        /* Verify failed */
        return -1;
    }
}
js4nwp54

js4nwp543#

我不知道你的有什么问题,但有一件事是肯定的,你需要在解密消息之前调用AES_set_decrypt_key()。另外,不要尝试打印为%s,因为加密的消息不再由ascii字符组成。例如:

static const unsigned char key[] = {
    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
    0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};

int main()
{
    unsigned char text[]="hello world!";
    unsigned char enc_out[80];
    unsigned char dec_out[80];

    AES_KEY enc_key, dec_key;

    AES_set_encrypt_key(key, 128, &enc_key);
    AES_encrypt(text, enc_out, &enc_key);      

    AES_set_decrypt_key(key,128,&dec_key);
    AES_decrypt(enc_out, dec_out, &dec_key);

    int i;

    printf("original:\t");
    for(i=0;*(text+i)!=0x00;i++)
        printf("%X ",*(text+i));
    printf("\nencrypted:\t");
    for(i=0;*(enc_out+i)!=0x00;i++)
        printf("%X ",*(enc_out+i));
    printf("\ndecrypted:\t");
    for(i=0;*(dec_out+i)!=0x00;i++)
        printf("%X ",*(dec_out+i));
    printf("\n");

    return 0;
}

U1:你的密钥是192位的,不是吗?

iyfjxgzm

iyfjxgzm4#

我的建议是逃跑

openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin

在调试器下,看看它到底在做什么。openssl.c是OpenSSL唯一真实的的教程/入门/参考指南。所有其他文档只是一个API参考。
U1:我猜你没有设置其他一些必需的选项,比如操作模式(填充)。
U2:这可能是这个问题的重复:AES CTR 256 Encryption Mode of operation on OpenSSL和答案可能会有帮助。

相关问题