Linux下使用openssl源码中的RSA加密算法

teat328 2011-03-09 03:53:36
openssl中集成了多种加密算法,包括对称加密,非对称加密,哈希等。最近的工作要在openssl的源码包中提取出RSA加密算法的代码,改写后,达到对文件加密解密的功能。
下载了openssl的源码包解压后,apps目录和crypto目录下都有相关RSA的代码。我该用哪一个?怎么才能编译通过?
对Linux下开发还不是太熟悉。。希望大虾们多多指点。。多谢。。
...全文
743 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Tom_殇子 2012-04-18
  • 打赏
  • 举报
回复
编译的时候要加参数:-lcrypto 你试试看。你最好把报错的图给我看看。
平凡的思想者 2011-03-10
  • 打赏
  • 举报
回复
加密:

/*
gcc -o rsa-encrypt rsa-encrypt.c -lcrypto
*/
#include <openssl/rsa.h>
#include <openssl/err.h>

#define MODULUS "C8FBCF21"
#define PUBLIC_EXPONENT RSA_F4
#define PRIVATE_EXPONENT "97B55D7D"

int main()
{
int ret, flen;
BIGNUM *bnn, *bne, *bnd;
unsigned char *in = "abc";
unsigned char *out;

bnn = BN_new();
bne = BN_new();
bnd = BN_new();
BN_hex2bn(&bnn, MODULUS);
BN_set_word(bne, PUBLIC_EXPONENT);
BN_hex2bn(&bnd, PRIVATE_EXPONENT);

RSA *r = RSA_new();
r->n = bnn;
r->e = bne;
r->d = bnd;
RSA_print_fp(stdout, r, 5);

flen = RSA_size(r);// - 11;

out = (char *)malloc(flen);
bzero(out, flen);
//memset(out, 0, flen);


printf("Begin encrypt...\n");
ret = RSA_public_encrypt(flen, in, out, r, RSA_NO_PADDING);
if (ret < 0)
{
printf("Encrypt failed!\n");
return 1;
}

printf("Size:%d\n", ret);
printf("ClearText:%s\n", in);
printf("CipherText(Hex):\n");
int i;
for (i=0; i<ret; i++)
{
printf("0x%02x, ", *out);
out++;
}
printf("\n");

//free(out);

RSA_free(r);
return 0;
}





解密:

/*
gcc -o rsa-decrypt rsa-decrypt.c -lcrypto
*/
#include <openssl/rsa.h>

#define MODULUS "C8FBCF21"
#define PUBLIC_EXPONENT RSA_F4
#define PRIVATE_EXPONENT "97B55D7D"

int main()
{
int ret, flen;
BIGNUM *bnn, *bne, *bnd;
unsigned char in[] = {0x51, 0xc2, 0x8d, 0xc6};
unsigned char *out;

bnn = BN_new();
bne = BN_new();
bnd = BN_new();
BN_hex2bn(&bnn, MODULUS);
BN_set_word(bne, PUBLIC_EXPONENT);
BN_hex2bn(&bnd, PRIVATE_EXPONENT);

RSA *r = RSA_new();
r->n = bnn;
r->e = bne;
r->d = bnd;
RSA_print_fp(stdout, r, 5);

flen = RSA_size(r);
out = (unsigned char *)malloc(flen);
bzero(out, flen);

printf("Begin decrypt...\n");
ret = RSA_private_decrypt(sizeof(in), in, out, r, RSA_NO_PADDING);
if (ret < 0)
{
printf("Decrypt failed!\n");
return 1;
}

printf("Size:%d\n", ret);
printf("ClearText:%s\n", out);

free(out);
RSA_free(r);
return 0;
}
大牛~Daniel 2011-03-09
  • 打赏
  • 举报
回复
移植啊!这个要有点耐心,淡定!
「已注销」 2011-03-09
  • 打赏
  • 举报
回复
用crypto这个吧。。。

23,110

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧