参考资料 http://blog.csdn.net/justinjing0612/article/details/7770315
+(void)initialize {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//可选项1。根据证书的路径获取public_key
NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
NSData *publicKeyData = [[NSData alloc] initWithContentsOfFile:publicKeyPath];
//可选项2。直接用静态(经base64加密)的公钥得到public_key
// NSData *publicKeyData = [GTMBase64 decodeString:RSA_KEY_BASE64];
SecCertificateRef certificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)publicKeyData);
if ( certificate ) {
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
SecTrustResultType trustResult;
OSStatus status = SecTrustCreateWithCertificates(certificate, policy, &trust);
if ( status == noErr ) {
status = SecTrustEvaluate(trust, &trustResult);//校验自签名证书问题
}
_public_key = SecTrustCopyPublicKey(trust);
CFRelease(certificate);
CFRelease(policy);
CFRelease(trust);
}
});
}
// 获取公钥
+ (SecKeyRef)getPublicKey {
return _public_key;
}
// RSA加密文本
+ (NSData *)rsaEncryptString:(NSString*)plainText {
NSData *encryptedData = nil;
SecKeyRef publicKey = [self getPublicKey];//获取公钥
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);//公钥的长度
uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));//分配空间
memset(cipherBuffer, 0, cipherBufferSize * sizeof(uint8_t));//初始化0
uint8_t *nonce = (uint8_t *) [plainText UTF8String];//文本转化
OSStatus status = SecKeyEncrypt(publicKey,
kSecPaddingPKCS1,
nonce,
strlen((char *) nonce),
&cipherBuffer[0],
&cipherBufferSize);//公钥和文本融合加密
if (status == noErr) {
encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];//如果转化成功就会转化成nsdata
}
if ( cipherBuffer ) {
free(cipherBuffer);//释放空间
}
NSLog(@"Encrypted text (%@ bytes): %@", @(encryptedData.length), encryptedData.description);
return encryptedData;
}