通常我们使用iOS的RSA加密或者解密时候,有如下几种情况(这里只讨论使用公钥加密的情况):
- 带公钥的证书
- PEM的格式public key(base64编码的PEM格式的公钥)
- DER格式的二进制字符串公钥
- 只有公钥的模n和公开幂e(通常是给的16进制Data数据)
带公钥证书,PEM格式publickey,DER格式的二进制字符串加密方法
iOS能够支持的带公钥的证书只能支持 --- 二进制编码格式的DER的X.509格式的证书.因此如果给予的证书格式是PEM格式,请参考本博客其他的RSA相关的文章,将PEM格式转化成DER格式.
#import "RSAEncryptor.h"
#import
@implementation RSAEncryptor
/**
讲传入的二进制数据,编码成base64格式的字符串
@param data 需要编码的二进制数据
@return base64编码以后的string
*/
static NSString *base64_encode_data(NSData *data){
data = [data base64EncodedDataWithOptions:0];
NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return ret;
}
/**
将base64编码的String,解码成二进制数据
@param str base64编码以后的数据
@return 原始二进制数据
*/
static NSData *base64_decode(NSString *str){
NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
return data;
}
#pragma mark - 使用'.der'公钥证书文件加密
/**
公钥加密的核心方法
传入二进制编码的der格式的带publickey的证书,给str参数的字符串进行RSA加密
@param str 待加密的字符串
@param path publickey证书路径
@return 加密以后的字符串
*/
+ (NSString *)encryptString:(NSString *)str publicKeyWithContentsOfFile:(NSString *)path{
if (!str || !path) return nil;
return [self encryptString:str publicKeyRef:[self getPublicKeyRefWithContentsOfFile:path]];
}
/**
工具方法
传入der格式的带有公钥的证书,该方法从证书中获取公钥
@param filePath 二进制编码的der格式带公钥的证书
@return 公钥对象
*/
+ (SecKeyRef)getPublicKeyRefWithContentsOfFile:(NSString *)filePath{
// 1. 获取der证书二进制数据
NSData *certData = [NSData dataWithContentsOfFile:filePath];
if (!certData) {
return nil;
}
// 2. 通过创建SecCertificateRef证书对象(这是c接口,因此需要手动管理对象的释放)
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (CFDataRef)certData);
SecKeyRef key = NULL;
SecTrustRef trust = NULL;
SecPolicyRef policy = NULL;
if (cert != NULL) {
// 3. 根据证书数据,证书策略 -> 信任管理对象, 设置的证书的策略是否是X.509证书(HTTPS中策略使用的是SSL策略)
policy = SecPolicyCreateBasicX509();
if (policy) {
if (SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) {
SecTrustResultType result;
if (SecTrustEvaluate(trust, &result) == noErr) {
// 4. 从证书评估对象中获取公钥SecKeyRef的引用,注意使用的copy,因此需要手动释放
key = SecTrustCopyPublicKey(trust);
}
}
}
}
if (policy) CFRelease(policy);
if (trust) CFRelease(trust);
if (cert) CFRelease(cert);
return key;
}
/**
加密核心方法
传入需要加密的字符串
@param str 需要加密的字符串
@param publicKeyRef 公钥SecKeyRef引用对象
@return 加密以后的数据
*/
+ (NSString *)encryptString:(NSString *)str publicKeyRef:(SecKeyRef)publicKeyRef{
//1. 参数检查
if(![str dataUsingEncoding:NSUTF8StringEncoding]){
return nil;
}
if(!publicKeyRef){
return nil;
}
//2. 待加密字符->二进制 -> 加密以后返回二进制加密数据
NSData *data = [self encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] withKeyRef:publicKeyRef];
//3. 加密以后二进制数据->base64编码的字符串
NSString *ret = base64_encode_data(data);
return ret;
}
#pragma mark - 使用公钥字符串加密
/* START: Encryption with RSA public key */
/**
使用RSA public key(非证书)进行加密
@param str 需要加密的字符串
@param pubKey 公钥字符串(格式PEM格式的publickey字符串)
@return 返回加密以后的字符串
*/
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey{
//1.调用核心方法将待加密的字符串转化成二进制数据,返回加密以后的二进制数据
NSData *data = [self encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];
//2.将加密以后的二进制数据通过base64编码以后的string返回,便于传输
NSString *ret = base64_encode_data(data);
return ret;
}
/**
通过PEM格式的public key 加密二进制数据,输出加密以后的二进制数据
@param data 待加密的二进制数据
@param pubKey PEM格式的public key
@return rsa加密以后的二进制数据
*/
+ (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey{
if(!data || !pubKey){
return nil;
}
//1.将PEM格式的public key数据生成SecKeyRef对象
SecKeyRef keyRef = [self addPublicKey:pubKey];
if(!keyRef){
return nil;
}
//2.传入待加密二进制数据和SecKeyRef公钥对象
return [self encryptData:data withKeyRef:keyRef];
}
/**
将PEM格式public key的string创建SecKeyRef对象
@param key PEM格式public key的string
@return SecKeyRef对象
*/
+ (SecKeyRef)addPublicKey:(NSString *)key{
//1. 找到PEM格式publickey的头部和尾部
NSRange spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
NSRange epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];
//2. 如果找到头部和尾部,那么截取头部尾部之间的部分 -- 真正的有用的public key部分
if(spos.location != NSNotFound && epos.location != NSNotFound){
NSUInteger s = spos.location + spos.length;
NSUInteger e = epos.location;
NSRange range = NSMakeRange(s, e-s);
key = [key substringWithRange:range];
}
//3. 清理PEM格式publickey中的"\r","\n"," "等回车,换行,空格字符
key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
//4. 一般PEM格式公钥字符串是通过base64编码以后的字符串,因此需要从中解码成原始二进制数据,解码以后是DER编码格式的
NSData *data = base64_decode(key);
//5. 清理DER格式的publickey的公钥头部信息 -- DER公钥满足ASN.1编码格式,具体参考TLV方式
data = [self stripPublicKeyHeader:data];
if(!data){
return nil;
}
//6. 下面将使用iOS的keychain中的内容处理公钥
//7. tag表示写入keychain的Tag标签,方便以后从keychain中读写这个公钥
NSString *tag = @"RSAUtil_PubKey";
NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
//8. 先删除keychain中的tag同名的对应的key
NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
// kSecClass是表示keychain中存储的类型,常见的有kSecClassGenericPassword(一般密码),kSecClassInternetPassword(网络密码),kSecClassCertificate(证书),kSecClassKey(密钥),kSecClassIdentity(带私钥证书)等
// 不同类型的钥匙串项对应的属性不同,这里使用的kSecClassKey(密钥),对应的属性有许多最重要的是kSecAttrKeyType,表示密钥的类型,这里使用的kSecAttrKeyTypeRSA;
[publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
[publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];// 设置需要删除的带tag的密钥
SecItemDelete((__bridge CFDictionaryRef)publicKey);// 先查询keychain中是否有同tag的,直接删除
[publicKey setObject:data forKey:(__bridge id)kSecValueData];//设置keychain的写入字段的类型kSecValueData
[publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)
kSecAttrKeyClass];//设置加密密钥类kSecAttrKeyClassPublic,kSecAttrKeyClassPrivate或者kSecAttrKeyClassSymmetric,这里是公钥
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
kSecReturnPersistentRef];//设置是否返回持久型实例(CFDataRef)
//9. 讲public key dict通过SecItemAdd添加到keychain中
CFTypeRef persistKey = nil;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
if (persistKey != nil){
CFRelease(persistKey);
}
if ((status != noErr) && (status != errSecDuplicateItem)) {
return nil;
}
[publicKey removeObjectForKey:(__bridge id)kSecValueData];// 清理属性
[publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];// 清理属性
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];//设置返回实例(SecKeychainItemRef, SecKeyRef, SecCertificateRef, SecIdentityRef, or CFDataRef)
[publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];// 这里其实原来已经添加过...
//10. 从keychain中获取SecKeyRef对象
SecKeyRef keyRef = nil;
status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
if(status != noErr){
return nil;
}
return keyRef;
}
/**
传入二进制的DER格式的公钥(包含header),返回去除头部的密钥的二进制形式
这里DER公钥的二进制格式TLV格式的,可以参考我的一篇博客http://www.jianshu.com/p/25803dd9527d
@param d_key 二进制的DER格式的公钥
@return
*/
+ (NSData *)stripPublicKeyHeader:(NSData *)d_key{
// Skip ASN.1 public key header
if (d_key == nil) return(nil);
unsigned long len = [d_key length];
if (!len) return(nil);
unsigned char *c_key = (unsigned char *)[d_key bytes];
unsigned int idx = 0;
//1.此时密钥一定是0x30开头的,或者说第一个字节一定是30(16进制)
if (c_key[idx++] != 0x30) return(nil);
//2.第二个字节一定是81或者82,81代表长度用1byte表示,82代表长度用2byte表示(此字节部分tag后不存在
if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
else idx++;
//3. 默认使用PKCS1填充格式,使用公共的头部数据填充:300d06092a864886f70d0101010500
// PKCS #1 rsaEncryption szOID_RSA_RSA
static unsigned char seqiod[] =
{ 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
0x01, 0x05, 0x00 };
if (memcmp(&c_key[idx], seqiod, 15)) return(nil);
idx += 15;
//4. 然后这里又是一个TLV格式,和开始类似0382010d
if (c_key[idx++] != 0x03) return(nil);
if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
else idx++;
//5. 这里需要补充00,具体参考我的其他博客
if (c_key[idx++] != '\0') return(nil);
//6. 返回的就是TLV中的value值,就是最后的内容
return ([NSData dataWithBytes:&c_key[idx] length:len - idx]);
}
/**
使用SecKeyRef对象加密核心方法
@param data 待加密二进制数据
@param keyRef 密钥SecKeyRef对象
@return RSA加密以后二进制数据
*/
+ (NSData *)encryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
const uint8_t *srcbuf = (const uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
// 加密block_size
size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
void *outbuf = malloc(block_size);
size_t src_block_size = block_size - 11;
NSMutableData *ret = [[NSMutableData alloc] init];
for(int idx=0; idx src_block_size){
data_len = src_block_size;
}
size_t outlen = block_size;
OSStatus status = noErr;
status = SecKeyEncrypt(keyRef,
kSecPaddingPKCS1,
srcbuf + idx,
data_len,
outbuf,
&outlen
);
if (status != 0) {
NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
ret = nil;
break;
}else{
[ret appendBytes:outbuf length:outlen];
}
}
free(outbuf);
CFRelease(keyRef);
return ret;
}
/* END: Encryption with RSA public key */
#pragma mark - 使用'.12'私钥文件解密
//解密
+ (NSString *)decryptString:(NSString *)str privateKeyWithContentsOfFile:(NSString *)path password:(NSString *)password{
if (!str || !path) return nil;
if (!password) password = @"";
return [self decryptString:str privateKeyRef:[self getPrivateKeyRefWithContentsOfFile:path password:password]];
}
//获取私钥
+ (SecKeyRef)getPrivateKeyRefWithContentsOfFile:(NSString *)filePath password:(NSString*)password{
NSData *p12Data = [NSData dataWithContentsOfFile:filePath];
if (!p12Data) {
return nil;
}
SecKeyRef privateKeyRef = NULL;
NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
[options setObject: password forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data, (__bridge CFDictionaryRef)options, &items);
if (securityError == noErr && CFArrayGetCount(items) > 0) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
if (securityError != noErr) {
privateKeyRef = NULL;
}
}
CFRelease(items);
return privateKeyRef;
}
+ (NSString *)decryptString:(NSString *)str privateKeyRef:(SecKeyRef)privKeyRef{
NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
if (!privKeyRef) {
return nil;
}
data = [self decryptData:data withKeyRef:privKeyRef];
NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return ret;
}
#pragma mark - 使用私钥字符串解密
/* START: Decryption with RSA private key */
//使用私钥字符串解密
+ (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey{
if (!str) return nil;
NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
data = [self decryptData:data privateKey:privKey];
NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return ret;
}
+ (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey{
if(!data || !privKey){
return nil;
}
SecKeyRef keyRef = [self addPrivateKey:privKey];
if(!keyRef){
return nil;
}
return [self decryptData:data withKeyRef:keyRef];
}
+ (SecKeyRef)addPrivateKey:(NSString *)key{
NSRange spos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
NSRange epos = [key rangeOfString:@"-----END RSA PRIVATE KEY-----"];
if(spos.location != NSNotFound && epos.location != NSNotFound){
NSUInteger s = spos.location + spos.length;
NSUInteger e = epos.location;
NSRange range = NSMakeRange(s, e-s);
key = [key substringWithRange:range];
}
key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
// This will be base64 encoded, decode it.
NSData *data = base64_decode(key);
data = [self stripPrivateKeyHeader:data];
if(!data){
return nil;
}
//a tag to read/write keychain storage
NSString *tag = @"RSAUtil_PrivKey";
NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
// Delete any old lingering key with the same tag
NSMutableDictionary *privateKey = [[NSMutableDictionary alloc] init];
[privateKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
[privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[privateKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
SecItemDelete((__bridge CFDictionaryRef)privateKey);
// Add persistent version of the key to system keychain
[privateKey setObject:data forKey:(__bridge id)kSecValueData];
[privateKey setObject:(__bridge id) kSecAttrKeyClassPrivate forKey:(__bridge id)
kSecAttrKeyClass];
[privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
kSecReturnPersistentRef];
CFTypeRef persistKey = nil;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)privateKey, &persistKey);
if (persistKey != nil){
CFRelease(persistKey);
}
if ((status != noErr) && (status != errSecDuplicateItem)) {
return nil;
}
[privateKey removeObjectForKey:(__bridge id)kSecValueData];
[privateKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
[privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
[privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef = nil;
status = SecItemCopyMatching((__bridge CFDictionaryRef)privateKey, (CFTypeRef *)&keyRef);
if(status != noErr){
return nil;
}
return keyRef;
}
+ (NSData *)stripPrivateKeyHeader:(NSData *)d_key{
// Skip ASN.1 private key header
if (d_key == nil) return(nil);
unsigned long len = [d_key length];
if (!len) return(nil);
unsigned char *c_key = (unsigned char *)[d_key bytes];
unsigned int idx = 22; //magic byte at offset 22
if (0x04 != c_key[idx++]) return nil;
//calculate length of the key
unsigned int c_len = c_key[idx++];
int det = c_len & 0x80;
if (!det) {
c_len = c_len & 0x7f;
} else {
int byteCount = c_len & 0x7f;
if (byteCount + idx > len) {
//rsa length field longer than buffer
return nil;
}
unsigned int accum = 0;
unsigned char *ptr = &c_key[idx];
idx += byteCount;
while (byteCount) {
accum = (accum << 8) + *ptr;
ptr++;
byteCount--;
}
c_len = accum;
}
// Now make a new NSData from this buffer
return [d_key subdataWithRange:NSMakeRange(idx, c_len)];
}
+ (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
const uint8_t *srcbuf = (const uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
UInt8 *outbuf = malloc(block_size);
size_t src_block_size = block_size;
NSMutableData *ret = [[NSMutableData alloc] init];
for(int idx=0; idx src_block_size){
data_len = src_block_size;
}
size_t outlen = block_size;
OSStatus status = noErr;
status = SecKeyDecrypt(keyRef,
kSecPaddingNone,
srcbuf + idx,
data_len,
outbuf,
&outlen
);
if (status != 0) {
NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
ret = nil;
break;
}else{
//the actual decrypted data is in the middle, locate it!
int idxFirstZero = -1;
int idxNextZero = (int)outlen;
for ( int i = 0; i < outlen; i++ ) {
if ( outbuf[i] == 0 ) {
if ( idxFirstZero < 0 ) {
idxFirstZero = i;
} else {
idxNextZero = i;
break;
}
}
}
[ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];
}
}
free(outbuf);
CFRelease(keyRef);
return ret;
}
/* END: Decryption with RSA private key */
@end
参考: https://github.com/ideawu/Objective-C-RSA
只有公钥的模n和公开幂e
当只有模n和公开幂e的时候,如果后台使用的JAVA,比较常见的情况是传递一个xml,内部包含公钥的长度,模n,以及幂e(有可能是base64的string,或者16进制data)下面的就有一个通用格式和一个实例:
1024
xxxxxxxxxxxxxxxxxxxxx
xxxx
yOTe0L1/NcbXdZYwliS82MiTE8VD5WD23S4RDsdbJOFzCLbsyb4d+K1M5fC+xDfCkji1zQjPiiiToZ7JSj/2ww==
AWAB
iOS系统的库不支持直接使用模n和幂e直接对数据进行加密.但是有大神开源了这个库SCZ-BasicEncodingRules-iOS.这个库的作用是通过已知的RSA的公钥的modulus和exponent,创建一个RSA的public key.下面是调用方法:
//注意使用这个库之前需要将base64的string转化成nsdata数据
// pubKeyModData 模n的二进制表示
// pubKeyExpData 幂e的二进制表示
NSMutableArray *testArray = [[NSMutableArray alloc] init];
[testArray addObject:pubKeyModData];
[testArray addObject:pubKeyExpData];
NSData *testPubKey = [testArray berData];
然后,将刚刚生成的publickey data写入keychain中,其他步骤见上节:
NSString * peerName = @"Test Public Key";
NSData * peerTag = [[NSData alloc] initWithBytes:(const void *)[peerName UTF8String] length:[peerName length]];
NSMutableDictionary * peerPublicKeyAttr = [[NSMutableDictionary alloc] init];
[peerPublicKeyAttr
setObject:(__bridge id)kSecClassKey
forKey:(__bridge id)kSecClass];
[peerPublicKeyAttr
setObject:(__bridge id)kSecAttrKeyTypeRSA
forKey:(__bridge id)kSecAttrKeyType];
[peerPublicKeyAttr
setObject:peerTag
forKey:(__bridge id)kSecAttrApplicationTag];
[peerPublicKeyAttr
setObject:testPubKey
forKey:(__bridge id)kSecValueData];
[peerPublicKeyAttr
setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecReturnPersistentRef];
sanityCheck = SecItemAdd((__bridge CFDictionaryRef) peerPublicKeyAttr, (CFTypeRef *)&persistPeer);
这里有一个使用上述方式的一个Demo工程:RSAPublicKey.核心方法如下:
SecKeyRef pubKey = [RSAPubKey stringToRSAPubKey:@"0E8fPw5rw/t1xobyTbXtZgLNYuBlX3RQy4re0SZerVGNW/LkN92Ycw+aLT0/9bxy/WuY63JOJFmZFVsIAnKhdfZLCoFQPq5nNJ1rUNfJ4J7FWvJoaM69IM/VA3GTdIRGQHgQJIXlXbiGOk+lJfo51Ncb67w2miqucsoS/YcgL0=" andExponent:@"AQAB"];
@implementation RSAPubKey
+ (SecKeyRef) stringToRSAPubKey: (NSString*) modulus andExponent:(NSString*) exponent
{
NSData* modulusData = [NSData dataWithBase64EncodedString: modulus];
NSData* exponentData = [NSData dataWithBase64EncodedString: exponent];
return [RSAPubKey dataRSAPubKey: modulusData andExponent: exponentData];
}
+ (SecKeyRef) dataRSAPubKey: (NSData*) modulus andExponent:(NSData*) exponent
{
if( modulus == nil || exponent == nil)
return nil;
NSMutableArray *testArray = [[NSMutableArray alloc] init];
const char fixByte = 0;
NSMutableData * fixedModule = [NSMutableData dataWithBytes:&fixByte length:1];
[fixedModule appendData:modulus];
[testArray addObject:fixedModule];
[testArray addObject:exponent];
NSData *pubKey = [testArray berData];
if( pubKey == nil ) {
return nil;
}
//a tag to read/write keychain storage
NSString *tag = @"LiveStorage_PubKey";
NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
// Delete any old lingering key with the same tag
NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
[publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
[publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
SecItemDelete((__bridge CFDictionaryRef)publicKey);
// Add persistent version of the key to system keychain
[publicKey setObject:pubKey forKey:(__bridge id)kSecValueData];
[publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id) kSecAttrKeyClass];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id) kSecReturnPersistentRef];
CFTypeRef persistKey = nil;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
if (persistKey != nil){
CFRelease(persistKey);
}
if ((status != noErr) && (status != errSecDuplicateItem)) {
return nil;
}
publicKey = [[NSMutableDictionary alloc] init];
[publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
[publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
[publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef = nil;
status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
if(status != noErr){
return nil;
}
return keyRef;
}
@end
或者我们可以创建一个base64编码的PEM格式的public key:
{
NSString *modulusString = @"c19bccae1e67743fab1c978f03122fb1a78ef05d565a2964728062ad0365e4751b8253df5fd13ab4ecb95c81ff17b91f969e4fb3d8274c30533338684278f6e5548027df775c055943a24a4117b0274c296c68b722c71670d4b21489a3da05d37ba06f2fb771b671a2c746bae4a049dc718fba19a75f1fb8ae1dd715b33d66a3";
NSString *exponentString = @"010001";
NSData *pubKeyModData = bytesFromHexString(modulusString);
NSData *pubKeyExpData = bytesFromHexString(exponentString);
NSArray *keyArray = @[pubKeyModData, pubKeyExpData];
//Given that you are using SCZ-BasicEncodingRules-iOS:
NSData *berData = [keyArray berData];
NSLog(@"berData:\n%@", berData);
NSString *berBase64 = [berData base64EncodedStringWithOptions:0];
NSString *preamble = @"-----BEGIN CERTIFICATE REQUEST-----";
NSString *postamble = @"-----END CERTIFICATE REQUEST-----";
NSString *pem = [NSString stringWithFormat:@"%@\n%@\n%@", preamble, berBase64, postamble];
NSLog(@"pem:\n%@", pem);
}
NSData* bytesFromHexString(NSString * aString) {
NSString *theString = [[aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:nil];
NSMutableData* data = [NSMutableData data];
int idx;
for (idx = 0; idx+2 <= theString.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString* hexStr = [theString substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
if ([scanner scanHexInt:&intValue])
[data appendBytes:&intValue length:1];
}
return data;
}
QuickRSA开源库包括系统API以及OpenSSL完成
QuickRSA,可以通过iOS的系统API来获取RSA SecKeyRef,并且用来Enc/Dec:
@interface QRSecCrypto : NSObject
//1. 509 Cert
+ (SecKeyRef)RSASecKeyPubCopyWithX509CertData:(NSData *)certData;
//2. Import P12 for private key
+ (SecKeyRef)RSASecKeyPriCopyWithP12Data:(NSData *)p12Data password:(NSString *)password;
//3. Use Keychain
+ (SecKeyRef)RSASecKeyCopyWithPKCS1Data:(NSData *)pkcs1Data appTag:(NSString *)appTag isPublic:(BOOL)isPublic;
//4. Use System API (For iOS 10 and later only)
+ (SecKeyRef)RSASecKeyCopyWithDERData:(NSData *)derData isPublic:(BOOL)isPublic;
@end
@interface NSData(QRSecCrypto)
- (NSData *)RSAEncryptDataWithPublicKey:(SecKeyRef)publicKey;
- (NSData *)RSADecryptDataWithPrivateKey:(SecKeyRef)privateKey;
@end
也可以通过OpenSSL来进行RSA加密和解密,同时可以直接使用模modulus和幂exponent
@interface NSData(OpenSSL)
//Use PEM, Pub(Pri) Enc -> Pri(Pub) Dec
- (NSData *)OpenSSL_RSA_EncryptDataWithPEM:(NSData *)pemData isPublic:(BOOL)isPublic;//PEM key
- (NSData *)OpenSSL_RSA_DecryptDataWithPEM:(NSData *)pemData isPublic:(BOOL)isPublic;//PEM key
//Use DER, Pub(Pri) Enc -> Pri(Pub) Dec
- (NSData *)OpenSSL_RSA_EncryptDataWithDER:(NSData *)derData isPublic:(BOOL)isPublic;//DER key
- (NSData *)OpenSSL_RSA_DecryptDataWithDER:(NSData *)derData isPublic:(BOOL)isPublic;//DER key
//Use modulus exponent
- (NSData *)OpenSSL_RSA_DataWithPublicModulus:(NSData *)modulus exponent:(NSData *)exponent isDecrypt:(BOOL)isDecrypt;
@end
同时,该库提供了QRFormatConvert
类,进行如下类型的转换:
- PEM <-> DER
- modulus, exponent <-> DER
- PKCS1 <-> DER
- Data <->Hex string
参考
- http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/
- http://stackoverflow.com/questions/7255991/rsa-encryption-public-key
- http://stackoverflow.com/questions/29669858/generate-rsa-public-key-from-modulus-and-exponent
- https://github.com/StCredZero/SCZ-BasicEncodingRules-iOS
- https://github.com/yangtu222/RSAPublicKey
这里还有一个将模n和幂e转化成PEM 格式的 pubic key的工具:
https://superdry.apphb.com/tools/online-rsa-key-converter