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