前言:后臺老哥對接口的響應數(shù)據(jù)進行了RSA2加密,給老衲提供了一個.pem公鑰的文件浴鸿,以便我們獲取公鑰對api響應的內(nèi)容進行解析井氢。
#define PublicKeyFile [[NSBundle mainBundle] pathForResource:@"server_public" ofType:@"pem"]
//使用公鑰 .pem文件 對服務器RSA2 解密
+(NSString *)RSA2DecodingWithString:(NSString *)str //這里的str就是接口響應的數(shù)據(jù)一長串
{
unsigned char encrypted[2048];
bzero(encrypted, sizeof(encrypted));
NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:0];
// NSData *data = [NSData dataWithBytes:contentChar length:128];
//明文
char decrypted[2048];
//公鑰和私鑰文件
const char* pub_key = [PublicKeyFile UTF8String];
// 打開私鑰文件
FILE* pub_fp=fopen(pub_key,"r");
if(pub_fp==NULL){
printf("Open Failed!! The Priv_Key File :%s!\n", pub_key);
return nil;
}
// 從文件中讀取公鑰
RSA *rsa = PEM_read_RSA_PUBKEY(pub_fp, NULL, NULL, NULL);
if(rsa==NULL){
printf("Pub_Key Read Failure!!\n");
return nil;
}
// 用公鑰解密
int state = RSA_size(rsa);
state = RSA_public_decrypt(state, (unsigned char*)[data bytes], (unsigned char*)decrypted, rsa, RSA_PKCS1_PADDING);
if(state == -1){
printf("Decrypt Failed!!\n");
return nil;
}
fclose(pub_fp);
// 輸出解密后的明文
decrypted[state]=0;
NSString *result = [NSString stringWithUTF8String:decrypted];
// NSLog(@"---%@",result);
return result;
}
上面封裝的方法返回的是一個json字符串,需要進行對應格式的數(shù)據(jù)
NSData *jsonData = [RSAString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
//resultDic 就是我們想要的數(shù)據(jù)
以上參考自一個大大的博客岳链,具體地址忘記了花竞,sor ~~!