#include<stdlib.h>
#include<string.h>
#include<openssl/rsa.h>
#include<openssl/engine.h>
int?main(int?argc,?char*?argv[])
{
printf("openssl_test?begin\n");
RSA*?rsa=NULL;
char?originstr[]="hello\n";//這是我們需要加密的原始數據
//allocate?RSA?structure,首先需要申請壹個RSA結構題用於存放生成的公私鑰,這裏rsa就是這個結構體的指針
rsa?=?RSA_new();
if(rsa==NULL)
{
printf("RSA_new?failed\n");? return?-1;}
//generate?RSA?keys
BIGNUM*?exponent;
exponent?=?BN_new();//生成RSA公私鑰之前需要選擇壹個奇數(odd?number)來用於生成公私鑰
if(exponent?==NULL)
{
printf("BN_new?failed\n");?
goto?FAIL1;
}
if(0==BN_set_word(exponent,65537))//這裏選擇奇數65537
{
printf("BN_set_word?failed\n");? goto?FAIL1;}
//這裏modulus的長度選擇4096,小於1024的modulus長度都是不安全的,容易被破解
if(0==RSA_generate_key_ex(rsa,4096,exponent,NULL))?
{
printf("RSA_generate_key_ex?failed\n");?
goto?FAIL;?
}
char*?cipherstr?=?NULL;
//分配壹段空間用於存儲加密後的數據,這個空間的大小由RSA_size函數根據rsa算出
cipherstr?=?malloc(RSA_size(rsa));?
if(cipherstr==NULL)
{
printf("malloc?cipherstr?buf?failed\n");
goto?FAIL1;
}
//下面是實際的加密過程,最後壹個參數padding?type,有以下幾種。
/*
RSA_PKCS1_PADDINGPKCS?#1?v1.5?padding.?This?currently?is?the?most?widely?used?mode.
RSA_PKCS1_OAEP_PADDING
EME-OAEP?as?defined?in?PKCS?#1?v2.0?with?SHA-1,?MGF1?and?an?empty?encoding?parameter.?This?mode?is?recommended?for?all?new?applications.
RSA_SSLV23_PADDING
PKCS?#1?v1.5?padding?with?an?SSL-specific?modification?that?denotes?that?the?server?is?SSL3?capable.
RSA_NO_PADDING
Raw?RSA?encryption.?This?mode?should?only?be?used?to?implement?cryptographically?sound?padding?modes?in?the?application?code.?Encrypting?user?data?directly?with?RSA?is?insecure.
*/?
//這裏首先用公鑰進行加密,選擇了RSA_PKCS1_PADDING if(RSA_size(rsa)!=RSA_public_encrypt(strlen(originstr)+1,originstr,cipherstr,rsa,RSA_PKCS1_PADDING)){
printf("encryption?failure\n");
goto?FAIL2;
}
printf("the?original?string?is?%s\n",originstr);
printf("the?encrypted?string?is?%s\n",cipherstr);
//Now,?let's?decrypt?the?string?with?private?key
//下面來用私鑰解密,首先需要壹個buffer用於存儲解密後的數據,這個buffer的長度要足夠(小於RSA_size(rsa))
//這裏分配壹個長度為250的字符數組,應該是夠用的。
char?decrypted_str[250];
int?decrypted_len;
if(-1=(decrypted_len=RSA_private_decrypt(256,cipherstr,decrypted_str,rsa,RSA_PKCS1_PADDING)))
{
printf("decryption?failure\n");
goto?FAIL2;
}
printf("decrypted?string?length?is?%d,decryped_str?is?%s\n",decrypted_len,decrypted_str);
FAIL2:
free(cipherstr);FAIL1:
BN_free(exponent);
FAIL:
RSA_free(rsa);
return?0;
}
以上是源代碼,下面使用下面的編譯命令在源碼所在路徑下生成可執行文件
gcc *.c -o openssl_test -lcrypto -ldl -L/usr/local/ssl/lib -I/usr/local/ssl/include
其中,-lcrypto和-ldl是必須的,前者是OpenSSL中的加密算法庫,後者是用於成功加載動態庫。