int test_rsa_encry() { #define RSA_KEY_FILE "rsakey.txt" // > openssl genrsa -out rsakey.txt 1024
RSA* key; char msg[]="i, i have no data to enc"; char msg2[256]; char msg3[256]; int r; //SSL_library_init();
//SSL_load_error_strings();
//OpenSSL_add_all_algorithms();
//key = RSA_new();
puts("genrsa...(maybe a few seconds)"); key = RSA_generate_key(1024, 65537, NULL, NULL); /* //测试写私钥 FILE *fp = fopen("private.txt", "w"); if (!PEM_write_RSAPrivateKey(fp, key, NULL, NULL, 0, 0, NULL)) { }
FILE *fppublic = fopen("public.txt", "w"); if (!PEM_write_RSAPublicKey(fppublic, key)) { } */ //der格式:
//公钥
unsigned char der[5000]={0}; int len=0; len = i2d_RSAPublicKey(key,NULL); len = i2d_RSAPublicKey(key, (unsigned char**)&der); //得到私钥 保存
len = i2d_RSAPrivateKey(key, (unsigned char**)&der);
FILE *fpder1 = fopen("publicKey-der.txt", "wb");
fwrite(der, 1, len, fpder1); fclose(fpder1);
FILE *fpder2 = fopen("privateKey-der.txt", "wb"); fwrite(der, 1, len, fpder2); fclose(fpder2);
puts("ok"); 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); printf("\nmsg2:\n");
for(int i=0; i<r; i++) { printf("%02x", (unsigned char)msg2[i]); }
if (!r) puts("error in enc");
r = RSA_private_decrypt(r, (unsigned char *)msg2, (unsigned char *)msg3, key, RSA_PKCS1_PADDING); if (!r) puts("error in dec"); if (memcmp(msg, msg3, strlen(msg))) puts("ERROR! text2 != text"); else { msg3[strlen(msg)] = 0; printf("\n解密后的明文:%s", msg3); } puts("\nis there errs? no? ok!"); RSA_free(key); return 0;
}
|