int test_rsa_crypt_from_file() { char msg[]="i, i have no data to enc"; char msg2[256]; int r;
//读公匙
RSA *key; FILE *fp = fopen("publickey.pem", "r"); //FILE *fp = fopen("public.txt", "r");//ok
if(fp == NULL) printf("fp error!"); key = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
r = RSA_public_encrypt(strlen(msg), (unsigned char *)msg, (unsigned char *)msg2, key, RSA_PKCS1_PADDING); // or RSA_PKCS1_OAEP_PADDING
FILE *fp1 = fopen("msg2.txt", "w"); fwrite(msg2,sizeof(unsigned char),r, fp1); fflush(fp1);
printf("\nmsg2:\n"); for(int i=0; i<r; i++) { printf("%02x", (unsigned char)msg2[i]); } printf("\n");
return 1; }
//解密
// ok
int test_rsa_decrypt_from_file() {
OpenSSL_add_all_algorithms(); //gengpeng-重要,有些算法必须这样初始化。
//-------------------------------------------------------
//需要openssl/applink.c文件
//读私钥
RSA *key; FILE *fp = fopen("private.txt", "r"); if(fp == NULL) printf("fp error!"); key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
RSA_print_fp(stdout,key,11); //--------------------------------------------------------
///////////////////////////////////////////////////////////////
//bio 读私匙
BIO * bp = NULL; RSA * r = NULL; bp = BIO_new(BIO_s_file()); BIO_read_filename(bp, "private.txt" ); r = PEM_read_bio_RSAPrivateKey(bp, NULL, NULL, NULL); BIO_free_all(bp); RSA_print_fp(stdout,r,11);
//读要解密的文件。
unsigned char msg2[1000], msg3[100]; int msg2len, msg3len; FILE *fpmsg = fopen("msg2.txt", "rb"); msg2len = fread( msg2, sizeof(unsigned char), 1000, fpmsg );
msg3len = RSA_private_decrypt(msg2len, (unsigned char *)msg2, (unsigned char *)msg3, key, RSA_PKCS1_PADDING);
msg3[msg3len] = 0; printf("解密后的明文:\n%s\n", msg3);
return 1;
}
|