参考http://blog.iamzsx.me/show.html?id=155002
针对于RSA加密,iOS端没有专门的支持RSA加密的接口(API),所以一般有俩种解决RSA加密的方案
一,通过制作自签名的x509证书,再调用x509的相关API进行加密
二,通过制作通用的pem的密钥结合openssl静态库进行RSA加密
在上一篇文章RSA加密(1.0)我们已经提到制作证书的过程,其中private_key.pem是私钥,public_key.der是用于iOS的公钥
下面讲一下x509加密
上篇文章我们制作了适用于iOS的公钥public_key.der与私钥private_key.p12,此处会用到这俩个密钥,创建一个工程,将俩个密钥引入到工程中。并导入Security.framework
#import <Foundation/Foundation.h>
#import <Security/Security.h>
@interface RSA : NSObject{
SecKeyRef publicKey;
SecCertificateRef certificate;
SecPolicyRef policy;
SecTrustRef trust;
size_t maxPlainLen;
}
- (NSData *)encryptWithData:(NSData *)content;
- (NSData *)encryptWithSting:(NSString *)content;
@end
#import "RSA.h"
#import <Security/Security.h>
@implementation RSA
- (id)init{
if (self = [super init]) {
NSString *public_keyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
if (public_keyPath == nil) {
NSLog(@"没有发现公钥");
return nil;
}
NSData *publicKeyFileContent = [NSData dataWithContentsOfFile:public_keyPath];
if (publicKeyFileContent == nil) {
NSLog(@"不能读取公钥内容");
return nil;
}
certificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)publicKeyFileContent);
if (certificate == nil) {
NSLog(@"不能读到证书");
return nil;
}
policy = SecPolicyCreateBasicX509();
OSStatus returnCode = SecTrustCreateWithCertificates(certificate, policy, &trust);
if (returnCode != 0) {
NSLog(@"SecTrustCreateWithCertificates失败.Error Code:%d",(int)returnCode);
return nil;
}
SecTrustResultType trustResultType;
returnCode = SecTrustEvaluate(trust, &trustResultType);
if (returnCode != 0) {
NSLog(@"SecTrustEvaluate失败.Error Code:%d",(int)returnCode);
return nil;
}
publicKey = SecTrustCopyPublicKey(trust);
if (publicKey == nil) {
NSLog(@"SecTrustCopyPublicKey fail");
return nil;
}
maxPlainLen = SecKeyGetBlockSize(publicKey)-12;
}
return self;
}
- (NSData *)encryptWithData:(NSData *)content{
size_t plainLen = [content length];
if (plainLen > maxPlainLen) {
NSLog(@"加密内容(%ld)太长,加密内容必须小于%ld",plainLen,maxPlainLen);
return nil;
}
void *plain = malloc(plainLen);
[content getBytes:plain length:plainLen];
size_t cipherLen = 128;//当前密钥长度是128字节
void *cipher = malloc(cipherLen);
OSStatus returnCode = SecKeyEncrypt(publicKey,kSecPaddingPKCS1, plain,plainLen, cipher, &cipherLen);
NSData *result = nil;
if (returnCode != 0) {
NSLog(@"SecKeyEncrypt失败.Error code:%d",(int)returnCode);
}else{
result = [NSData dataWithBytes:cipher length:cipherLen];
}
free(plain);
free(cipher);
return result;
}
- (NSData *)encryptWithSting:(NSString *)content{
return [self encryptWithData:[content dataUsingEncoding:NSUTF8StringEncoding]];
}
- (void)dealloc{
CFRelease(certificate);
CFRelease(trust);
CFRelease(policy);
CFRelease(publicKey);
}
@end
za