rsa-c++

rsa-c++

#include 
#include 

#include 
#include
#include
#include 
#include 
#include 
#include 
using namespace std;
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")

void generateKey() {

	/* 生成公钥 */
	RSA* rsa = RSA_generate_key( 1024, RSA_F4, NULL, NULL);
	BIO *bp = BIO_new( BIO_s_file() );
	BIO_write_filename( bp, "public.pem" );
	PEM_write_bio_RSAPublicKey(bp, rsa);
	BIO_free_all( bp );
	/* 生成私钥 */
	char passwd[]="1234";
	bp = BIO_new_file("private.pem", "w+");
	PEM_write_bio_RSAPrivateKey(bp, rsa, EVP_des_ede3(), (unsigned char*)passwd, 4, NULL, NULL);
	BIO_free_all( bp );
	RSA_free(rsa);
}

std::string bio_read_privateKey(string data) {
	OpenSSL_add_all_algorithms();
    
    BIO* bp = BIO_new( BIO_s_file() );
	
    BIO_read_filename( bp, "private.pem" );
    
    char passwd[]="1234";
    RSA* rsaK = PEM_read_bio_RSAPrivateKey( bp, NULL, NULL, passwd );
	if (NULL == rsaK) {
		perror("read key file fail!");
	}else{
		printf("read success!\n");
	}

	int nLen = RSA_size(rsaK);
	//printf("len:%d\n",nLen);
	char *pEncode = new char[nLen + 1];
	int ret = RSA_private_decrypt(data.length(),(const unsigned char*)data.c_str(),(unsigned char *)pEncode,rsaK,RSA_PKCS1_PADDING);
	std::string strRet;
	if (ret >= 0) {
		strRet = std::string(pEncode, ret);
		//printf("%s",strRet.c_str());
	}
	
	delete[] pEncode;
	CRYPTO_cleanup_all_ex_data();
	BIO_free_all( bp );
	RSA_free(rsaK);
	return strRet;
}

std::string bio_read_publicKey(string data){
	OpenSSL_add_all_algorithms();
    BIO* bp = BIO_new( BIO_s_file() );
    BIO_read_filename( bp, "public.pem" );
    RSA* rsaK = PEM_read_bio_RSAPublicKey( bp, NULL, NULL, NULL );
	if (NULL == rsaK) {
		perror("read key file fail!");
	}else{
		printf("read success!");
		int nLen = RSA_size(rsaK);
		printf("len:%d\n",nLen);
	}
	int nLen = RSA_size(rsaK);
	char *pEncode = new char[nLen + 1];
	int ret = RSA_public_encrypt(data.length(),(const unsigned char*)data.c_str(),
		(unsigned char *)pEncode,rsaK,RSA_PKCS1_PADDING);
	std::string strRet;
	if (ret >= 0) {
		strRet = std::string(pEncode, ret);
		//printf("%s\n",strRet.c_str());
	}
	delete[] pEncode;
	CRYPTO_cleanup_all_ex_data();
	BIO_free_all( bp );
	RSA_free(rsaK);
	return strRet;
}

void encryptFile(string inputfile,string outputfile){
	ifstream file(inputfile.c_str());
	ofstream outfile(outputfile.c_str());
	string tsum;
	string ss;
	while (getline(file,ss)) {
		tsum.append(ss.append("\n"));
	}
	cout<<"徐加密内容:"<


你可能感兴趣的:(c++,rsa)