项目需要,对c++代码中的几个用poenssl库实现的rsa加解密函数进行了整合。
rsa加密的public key格式有多种,常见的有两种,一种密钥头为‘-----BEGIN RSA PUBLIC KEY-----’,一种开头为‘-----BEGIN PUBLIC KEY-----’,二者分别对应rsa的PKCS#1和PKCS#8格式。
使用openssl库加载rsa的公钥时,使用的函数也不同。以字符串公钥为例,对PKCS#1格式的密钥加载使用PEM_read_bio_RSAPublicKey()函数,对PKCS#8格式公钥的加载使用PEM_read_bio_RSA_PUBKEY()函数。
对于不那么熟悉rsa的同学,使用时注意区分者,可以减少不必要的麻烦。
string Base64Encode_std(const string& encodeStr){
//ignore
}
string rsaEncode(const unsigned char * in, int len, const char *pubKey){
BIO *bio=NULL;
RSA *rsa = NULL;
char szOut[512] = {0};
string pkcs1_header = "-----BEGIN RSA PUBLIC KEY-----";
string pkcs8_header = "-----BEGIN PUNLIC KEY-----";
bio = BIO_bew(BIO_s_mem());
if (NULL == bio) return "";
BIO_puts(bio,pubKey);
if( 0 == strncmp(pubKey,pkcs8_header.c_str(),pkcs8.size())){