NSString *RSA_encrypt(NSString *data)
{
unsigned char *str=(unsigned char*)[data UTF8String]; //把要加密的数据进行utf8编码
unsigned char *p_en;
RSA *p_rsa;
int rsa_len;
NSString *public = formatPublicKey(PUBLIC_KEY); //把服务器的公钥格式化
NSData *pub= [public dataUsingEncoding: NSUTF8StringEncoding]; //公钥utf8编码
BIO *bio = BIO_new_mem_buf((void *)[pub bytes], (int)[pub length]); //用bio函数把编码过的公钥写到内存中
p_rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, 0, NULL); //用pem格式读取内存中的公钥
BIO_free(bio); //内存中释放bio
rsa_len=RSA_size(p_rsa); //计算公钥的长度
p_en=(unsigned char *)malloc(rsa_len+1); //分配公钥长度的内存
memset(p_en,0,rsa_len+1); //内存清零
int Result=RSA_public_encrypt((int)strlen((const char*)str),(unsigned char *)str,(unsigned char*)p_en,p_rsa,RSA_PKCS1_PADDING);
//加密公钥 int RSA_public_encrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);
if(Result<0)
return NULL;
RSA_free(p_rsa); //内存中释放p_rsa
NSMutableString *result = [NSMutableString stringWithCapacity:128]; //创建一个128字符的可变字符串
for(int i = 0; i < 128; i++)
[result appendFormat:@"%02x", (unsigned char)p_en[i]]; //把加密的Result存储到result中去
free(p_en); //内存中释放p_en
p_en=NULL;
return result;
}
利用openssl库进行RSA加密
最新推荐文章于 2024-05-29 18:46:00 发布