请问有没有c或c加加的openssl的rsa分段加密例子demo?超过117个字节的明文
- 提问者网友:原来太熟悉了会陌生
- 2021-11-07 13:46
- 五星知识达人网友:举杯邀酒敬孤独
- 2021-11-07 14:18
#include
#include
#include
#include
#include
int main(int argc, char* argv[])
{
printf("openssl_test begin
");
RSA* rsa=NULL;
char originstr[]="hello
"; //这是我们需要加密的原始数据
//allocate RSA structure,首先需要申请一个RSA结构题用于存放生成的公私钥,这里rsa就是这个结构体的指针
rsa = RSA_new();
if(rsa==NULL)
{
printf("RSA_new failed
");
return -1;
}
//generate RSA keys
BIGNUM* exponent;
exponent = BN_new(); //生成RSA公私钥之前需要选择一个奇数(odd number)来用于生成公私钥
if(exponent ==NULL)
{
printf("BN_new failed
");
goto FAIL1;
}
if(0==BN_set_word(exponent,65537)) //这里选择奇数65537
{
printf("BN_set_word failed
");
goto FAIL1;
}
//这里modulus的长度选择4096,小于1024的modulus长度都是不安全的,容易被破解
if(0==RSA_generate_key_ex(rsa,4096,exponent,NULL))
{
printf("RSA_generate_key_ex failed
");
goto FAIL;
}
char* cipherstr = NULL;
//分配一段空间用于存储加密后的数据,这个空间的大小由RSA_size函数根据rsa算出
cipherstr = malloc(RSA_size(rsa));
if(cipherstr==NULL)
{
printf("malloc cipherstr buf failed
");
goto FAIL1;
}
//下面是实际的加密过程,最后一个参数padding type,有以下几种。
//这里首先用公钥进行加密,选择了RSA_PKCS1_PADDING
if(RSA_size(rsa)!=RSA_public_encrypt(strlen(originstr)+1,originstr,cipherstr,rsa,RSA_PKCS1_PADDING))
{
printf("encryption failure
");
goto FAIL2;
}
printf("the original string is %s
",originstr);
printf("the encrypted string is %s
",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
");
goto FAIL2;
}
printf("decrypted string length is %d,decryped_str is %s
",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中的加密算法库,后者是用于成功加载动态库。