openssl中是否有任何C API可以从给定的字符串派生密钥

时间:2011-07-21 07:08:11

标签: c openssl

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

2 个答案:

答案 0 :(得分:5)

执行此操作的标准算法是PBKDF2(基于密码的密钥派生函数版本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);

生成新密钥时,应使用RAND_bytes()中的openssl/rand.h创建salt。 iter是迭代计数,应该与您的预期应用程序可以容忍的一样大 - 至少类似于20,000。

答案 1 :(得分:0)

我找到了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);
}