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加密
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.