在RSA使用过程中,公钥加密一般用来协商密钥;私钥加密一般用来签名。
Ø n:模数
Ø e:公钥指数
Ø d:私钥指数
n+e可以组成公钥
n+d可以组成私钥
代码包括
1。生成RSA的数据结构
2。用指定的n,e,d生成RSA的数据结构
3。用私钥加密
4。用公钥解密
5。SHA256报文摘要
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
void testRSAGen(){
RSA *r;
int bits=512,ret;
unsigned long e=RSA_3;
BIGNUM *bne;
r=RSA_generate_key(bits,e,NULL,NULL);
RSA_print_fp(stdout,r,11);
printf("--------------------------------/n");
RSA_free(r);
bne=BN_new();
ret=BN_set_word(bne,e);
r=RSA_new();
ret=RSA_generate_key_ex(r,bits,bne,NULL);
if(ret!=1)
{
printf("RSA_generate_key_ex err!/n");
return -1;
}
//RSA_print_fp(stdout,r,11);
RSA_free(r);
}
void testRSA(){
RSA *r;
BIGNUM *bne,*bnn,*bnd;
int bits = 1024, ret, len, flen, padding, i;
unsigned char *key, *p;
BIO *b;
//要加密的明文
unsigned char *in = "abcef";
unsigned char *encData,*decData,*tmpData;//加密后的数据/解密后的数据/临时指针
//使用的密匙数据
unsigned long e = 75011;
const char *MODULUS="...";
const char *PRIVATE="...";
//构建RSA数据结构
bne = BN_new();
bnd = BN_new();
bnn = BN_new();
ret = BN_set_word(bne, e);
BN_hex2bn(&bnd, PRIVATE);
BN_hex2bn(&bnn, MODULUS);
r = RSA_new();
r->e=bne;
r->d=bnd;
r->n=bnn;
RSA_print_fp(stdout, r, 5);
//准备输出的加密数据结构
flen = RSA_size(r);// - 11;
encData = (unsigned char *)malloc(flen);
bzero(encData, flen);//memset(encData, 0, flen);
printf("Begin RSA_private_encrypt .../n");
ret = RSA_private_encrypt(flen, in, encData, r, RSA_NO_PADDING);
if(ret < 0){
printf("Encrypt failed!/n");
return;
}
printf("Size:%d/n", ret);
printf("ClearText:%s/n", in);
printf("CipherText(Hex):/n");
tmpData=encData;
for (i=0; i<ret; i++){
printf("0x%02x, ", *tmpData);
tmpData++;
}
printf("end private encrypt /n");
printf("------------------------/n");
//准备输出的解密数据结构
flen = RSA_size(r);// - 11;
decData = (unsigned char *)malloc(flen);
bzero(decData, flen);//memset(encData, 0, flen);
printf("Begin RSA_public_decrypt .../n");
ret = RSA_public_decrypt(flen, encData, decData, r, RSA_NO_PADDING);
if(ret < 0){
printf("RSA_public_decrypt failed!/n");
return;
}
printf("Size:%d/n", ret);
printf("ClearText:%s/n", decData);
free(encData);
free(decData);
RSA_free(r);
}
void testSHA256(){
unsigned char in[]="asdfwerqrewrasfaser";
unsigned char out[32];
size_t n;
int i;
n=strlen((const char*)in);
SHA256(in,n,out);
printf("/n/nSHA256 digest result:/n");
printf("%d/n",sizeof(out));
for(i=0;i<32;i++)
printf("%d",out[i]);
printf("/n");
}
int main(void) {
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
testSHA256();
testRSA();
return EXIT_SUCCESS;
}