【问题标题】:Is there any C API in openssl to derive a key from given stringopenssl 中是否有任何 C API 从给定字符串派生密钥
【发布时间】:2011-10-09 23:46:19
【问题描述】:

我需要 openssl 库中的 C API 来从给定字符串派生密钥。我在哪里可以获得示例源代码?

【问题讨论】:

  • 你的意思是openssl API for C吗?我认为 OpenSSL 是一个具有一些 API 功能的库。如果我错了,请纠正我
  • 你的字符串是什么样的?你能举个例子吗?
  • 什么样的钥匙?你想根据一些文本密码生成对称加密密钥吗?例如。 en.wikipedia.org/wiki/PBKDF2 ?

标签: c openssl


【解决方案1】:

执行此操作的标准算法是 PBKDF2(Password-Based Key Derivation Function version 2 的首字母缩写)。 OpenSSL中有一个PBKDF2的实现,在openssl/evp.h中声明:

int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen,
                           unsigned char *salt, int saltlen, int iter,
                           int keylen, unsigned char *out);

当您生成新密钥时,您应该使用来自openssl/rand.hRAND_bytes() 来创建盐。 iter 是迭代计数,它应该与您的预期应用程序可以容忍的一样大 - 至少大约 20,000 次。

【讨论】:

  • 我如何从中获得静脉注射?
  • @user465139:你没有,你使用另一个调用 RAND_bytes() 来生成 IV。
  • @caf 依靠 RAND_bytes 生成 IV 是否安全? openssl 在内部有什么不同吗?
  • @saruftw:是的,它是安全的,RAND_bytes 是一个 CSPRNG。
【解决方案2】:

我找到了an example,了解如何从密码生成密钥。该示例可以追溯到 2008 年,据我所知,这在 OpenSSL 中仍然没有记录。因此,让我发布完整的示例源代码,以帮助所有尝试使用 OpenSSL API 的可怜人。

请注意,这不是我的代码,它来自 Marek Marcola!所有功劳都归功于他。

/*
 * Example program on how to derive an encryption key from a password
 * corresponding to the RFC2898 / PBKDF2 standard.
 * Found in a 2008 mailing list posted by Marek Marcola:
 * http://www.mail-archive.com/openssl-users@openssl.org/msg54143.html
 */

#include <string.h>

#include <openssl/x509.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>

int print_hex(unsigned char *buf, int len)
{
    int i;
    int n;

    for(i=0,n=0;i<len;i++){
        if(n > 7){
            printf("\n");
            n = 0;
        }
        printf("0x%02x, ",buf[i]);
        n++;
    }
    printf("\n");

    return(0);
}

int main()
{
    char *pass = "password";
    char *salt = "12340000";
    int ic = 1;
    unsigned char buf[1024];

    ic = 1;
    PKCS5_PBKDF2_HMAC_SHA1(pass, strlen(pass), (unsigned char*)salt, strlen(salt), ic, 32+16, buf);
    printf("PKCS5_PBKDF2_HMAC_SHA1(\"%s\", \"%s\", %d)=\n", pass, salt, ic);
    print_hex(buf, 32+16);

    ic = 1;
    EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), (unsigned char*)salt, (unsigned char*)pass, strlen(pass), ic, buf, buf+32);
    printf("EVP_BytesToKey(\"%s\", \"%s\", %d)=\n", pass, salt, ic);
    print_hex(buf, 32+16);

    return(0);
}

【讨论】:

猜你喜欢
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2021-10-24
相关资源
最近更新 更多