iOS_服务端提供.pem公钥文件,对API RSA2加密的数据解析

前言:后台老哥对接口的响应数据进行了RSA2加密,给老衲提供了一个.pem公钥的文件,以便我们获取公钥对api响应的内容进行解析。

#define PublicKeyFile [[NSBundle mainBundle] pathForResource:@"server_public" ofType:@"pem"]

//使用公钥 .pem文件 对服务器RSA2 解密 
+(NSString *)RSA2DecodingWithString:(NSString *)str //这里的str就是接口响应的数据一长串
{
    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字符串,需要进行对应格式的数据

NSData *jsonData = [RSAString dataUsingEncoding:NSUTF8StringEncoding];
 NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
//resultDic 就是我们想要的数据

以上参考自一个大大的博客,具体地址忘记了,sor ~~!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容