使用BIO API的OpenSSL EVP_aes_128_gcm

时间:2014-11-17 11:21:32

标签: c linux encryption openssl

我尝试将OpenSSL的BIO接口与AES GCM 128位加密模式一起使用。我几乎直接从一本书中复制了一个例子(Network Security with OpenSSL Example 4.8),只是将加密模式改为aes_128_gcm,但事情不起作用(写入一个空文件)。由于我是OpenSSL的新手,我可能会做些傻事。你可以告诉我下面的代码段中的错误:

int main()
{
    OpenSSL_add_all_algorithms();
    char *msg = "hello";
    return write_data("hello.out", msg, strlen(msg),  "1234567890123456");
}

int write_data(const char *filename, char *out, int len, unsigned char *key)
{
    int total, written;
    BIO *cipher, *b64, *buffer, *file;
    file = BIO_new_file(filename, "w");
    buffer = BIO_new(BIO_f_buffer());
    b64 = BIO_new(BIO_f_base64());
    cipher = BIO_new(BIO_f_cipher());
    BIO_set_cipher(cipher, EVP_aes_128_gcm(), key, NULL, 1);
    BIO_push(cipher, b64);
    BIO_push(b64, buffer);
    BIO_push(buffer, file);
    for (total = 0; total < len; total += written)
    {
        if ((written = BIO_write(cipher, out + total, len - total)) <= 0)
        {
            if (BIO_should_retry(cipher))
            {
                written = 0;
                continue;
            }
            break;
        }
    }
    BIO_flush(cipher);
    BIO_free_all(cipher);
}

我刚刚将EVP_des_ede3_cbc()从示例更改为EVP_aes_128_gcm() - 并将密钥更改为16个字符。

1 个答案:

答案 0 :(得分:1)

对不起,我想出来了。我传递了一个NULL作为IV - 这绝对是必需的 - 显然!