13,825
社区成员
发帖
与我相关
我的任务
分享
String Fetion::RSA_Encrypt(const char* modulus, int publicExponent, const char* pszClearText)
{
BIGNUM *bnn, *bne;
bnn = BN_new();
bne = BN_new();
BN_hex2bn(&bnn, modulus);
BN_set_word(bne, publicExponent);
RSA *rsa = RSA_new();
rsa->n = bnn;
rsa->e = bne;
int len = RSA_size(rsa);
unsigned char* pszCipherText = new unsigned char[len];
int nRet = RSA_public_encrypt(len-11, (const unsigned char*)pszClearText, pszCipherText, rsa, RSA_PKCS1_PADDING);
char *b=new char[nRet*2+1];
BinToHex((char *)pszCipherText,b,nRet);
b[nRet*2]='\0';
String hash=b;
delete []pszCipherText,b;
BN_clear_free(bnn);
BN_clear_free(bne);
return hash;
}
#include <string.h>
#include <memory.h>
#include <openssl/rsa.h>
#include <openssl/applink.c>
#include <openssl/pem.h>
#define PUBLICKEY "server.cer"
#define PRIVATEKEY "test.pfx"
int main()
{
CRYPTO_malloc_init();
OpenSSL_add_all_algorithms();
char* txt = "hello world!";
char outbuf[1024] = {0};
char what[1024] = {0};
FILE* public_file = fopen(PUBLICKEY, "r");
FILE* private_file = fopen(PRIVATEKEY, "r");
//加密
RSA* pubkey = PEM_read_RSAPublicKey(public_file, NULL, NULL, NULL);
int flen = RSA_size(pubkey);
int len = RSA_public_encrypt(flen, (unsigned char*)txt, (unsigned char*)outbuf, pubkey, RSA_NO_PADDING);
printf("Encrypt:%s\r\n", outbuf);
//解密
RSA* prikey = PEM_read_RSAPrivateKey(private_file, NULL, NULL, NULL);
flen = RSA_size(prikey);
len = RSA_private_decrypt(flen, (unsigned char*)outbuf, (unsigned char*)what, prikey, RSA_NO_PADDING);
printf("Decrypt:%s\r\n", what);
RSA_free(pubkey);
RSA_free(prikey);
return 0;
}
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/applink.c>
#define PUBFILE "server.cer"
#define PRIVFILE "test.pfx"
EVP_PKEY* ReadPublicKey(const char *certfile);
EVP_PKEY* ReadPrivateKey(const char *keyfile);
int main()
{
SSLeay_add_all_algorithms();
ERR_load_crypto_strings();
ReadPublicKey(PUBFILE);
return 0;
}
EVP_PKEY* ReadPublicKey(const char *certfile)
{
FILE *fp = fopen (certfile, "r");
X509 *x509;
EVP_PKEY *pkey;
if (NULL == fp)
{
return NULL;
}
x509 = PEM_read_X509(fp, NULL, 0, NULL);
fclose (fp);
if (NULL == x509)
{
return NULL;
}
pkey = X509_extract_key(x509);
X509_free(x509);
return pkey;
}
EVP_PKEY* ReadPrivateKey(const char *keyfile)
{
FILE *fp = fopen(keyfile, "r");
EVP_PKEY *pkey;
if (NULL == fp)
{
return NULL;
}
pkey = PEM_read_PrivateKey(fp, NULL, 0, NULL);
fclose (fp);
return pkey;
}