📄 demo_rsaenc.c
字号:
// demo how to enc a piece of data using RSA
// by Linden 0:23 2003-11-15
#include <openssl/md5.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <string.h>
main()
{
#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();
#if 1 // gen
puts("genrsa...(maybe a few seconds)");
key = RSA_generate_key(1024, 65537, NULL, NULL);
puts("ok");
#else // read in
{
#if 0 // 曾经ok过吗?忘了
FILE *fp = fopen(RSA_KEY_FILE, "r");
key = PEM_read_RSAPrivateKey(fp, &key, NULL, NULL);
#else
int i;
EVP_PKEY* k;
BIO *in = BIO_new(BIO_s_file_internal());
i = BIO_read_filename(in, RSA_KEY_FILE);
if (i<=0) puts("read key file err");
else
k = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
key = RSAPrivateKey_dup(k->pkey.rsa);
EVP_PKEY_free(k);
BIO_free(in);
#endif
}
#endif
#if 0 // display. there's err
{
//BIO *o = BIO_new_fd(fileno(stdout), BIO_NOCLOSE);
BIO *o = BIO_new(BIO_s_file());
RSA_print(o, key, 0);
BIO_free(o);
}
#endif
r = RSA_public_encrypt(strlen(msg), msg, msg2,
key, RSA_PKCS1_PADDING); // or RSA_PKCS1_OAEP_PADDING
if (!r) puts("error in enc");#if 0 sig[0]++; // 假想的错误#endif r = RSA_private_decrypt(r, msg2, 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("解密后的明文:%s", msg3);
}
puts("is there errs? no? ok!");
RSA_free(key);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -