通常我們使用iOS的RSA加密或者解密時候,有如下幾種情況(這里只討論使用公鑰加密的情況):
- 帶公鑰的證書
- PEM的格式public key(base64編碼的PEM格式的公鑰)
- DER格式的二進制字符串公鑰
- 只有公鑰的模n和公開冪e(通常是給的16進制Data數(shù)據(jù))
帶公鑰證書,PEM格式publickey,DER格式的二進制字符串加密方法
iOS能夠支持的帶公鑰的證書只能支持 --- 二進制編碼格式的DER的X.509格式的證書.因此如果給予的證書格式是PEM格式,請參考本博客其他的RSA相關(guān)的文章,將PEM格式轉(zhuǎn)化成DER格式.
#import "RSAEncryptor.h"
#import <Security/Security.h>
@implementation RSAEncryptor
/**
講傳入的二進制數(shù)據(jù),編碼成base64格式的字符串
@param data 需要編碼的二進制數(shù)據(jù)
@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,解碼成二進制數(shù)據(jù)
@param str base64編碼以后的數(shù)據(jù)
@return 原始二進制數(shù)據(jù)
*/
static NSData *base64_decode(NSString *str){
NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
return data;
}
#pragma mark - 使用'.der'公鑰證書文件加密
/**
公鑰加密的核心方法
傳入二進制編碼的der格式的帶publickey的證書,給str參數(shù)的字符串進行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證書二進制數(shù)據(jù)
NSData *certData = [NSData dataWithContentsOfFile:filePath];
if (!certData) {
return nil;
}
// 2. 通過<Security/Security.h>創(chuàng)建SecCertificateRef證書對象(這是c接口,因此需要手動管理對象的釋放)
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (CFDataRef)certData);
SecKeyRef key = NULL;
SecTrustRef trust = NULL;
SecPolicyRef policy = NULL;
if (cert != NULL) {
// 3. 根據(jù)證書數(shù)據(jù),證書策略 -> 信任管理對象, 設(shè)置的證書的策略是否是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 加密以后的數(shù)據(jù)
*/
+ (NSString *)encryptString:(NSString *)str publicKeyRef:(SecKeyRef)publicKeyRef{
//1. 參數(shù)檢查
if(![str dataUsingEncoding:NSUTF8StringEncoding]){
return nil;
}
if(!publicKeyRef){
return nil;
}
//2. 待加密字符->二進制 -> 加密以后返回二進制加密數(shù)據(jù)
NSData *data = [self encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] withKeyRef:publicKeyRef];
//3. 加密以后二進制數(shù)據(jù)->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.調(diào)用核心方法將待加密的字符串轉(zhuǎn)化成二進制數(shù)據(jù),返回加密以后的二進制數(shù)據(jù)
NSData *data = [self encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];
//2.將加密以后的二進制數(shù)據(jù)通過base64編碼以后的string返回,便于傳輸
NSString *ret = base64_encode_data(data);
return ret;
}
/**
通過PEM格式的public key 加密二進制數(shù)據(jù),輸出加密以后的二進制數(shù)據(jù)
@param data 待加密的二進制數(shù)據(jù)
@param pubKey PEM格式的public key
@return rsa加密以后的二進制數(shù)據(jù)
*/
+ (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey{
if(!data || !pubKey){
return nil;
}
//1.將PEM格式的public key數(shù)據(jù)生成SecKeyRef對象
SecKeyRef keyRef = [self addPublicKey:pubKey];
if(!keyRef){
return nil;
}
//2.傳入待加密二進制數(shù)據(jù)和SecKeyRef公鑰對象
return [self encryptData:data withKeyRef:keyRef];
}
/**
將PEM格式public key的string創(chuàng)建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編碼以后的字符串,因此需要從中解碼成原始二進制數(shù)據(jù),解碼以后是DER編碼格式的
NSData *data = base64_decode(key);
//5. 清理DER格式的publickey的公鑰頭部信息 -- DER公鑰滿足ASN.1編碼格式,具體參考TLV方式
data = [self stripPublicKeyHeader:data];
if(!data){
return nil;
}
//6. 下面將使用iOS的keychain中的內(nèi)容處理公鑰
//7. tag表示寫入keychain的Tag標簽,方便以后從keychain中讀寫這個公鑰
NSString *tag = @"RSAUtil_PubKey";
NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
//8. 先刪除keychain中的tag同名的對應(yīng)的key
NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
// kSecClass是表示keychain中存儲的類型,常見的有kSecClassGenericPassword(一般密碼),kSecClassInternetPassword(網(wǎng)絡(luò)密碼),kSecClassCertificate(證書),kSecClassKey(密鑰),kSecClassIdentity(帶私鑰證書)等
// 不同類型的鑰匙串項對應(yīng)的屬性不同,這里使用的kSecClassKey(密鑰),對應(yīng)的屬性有許多最重要的是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];// 設(shè)置需要刪除的帶tag的密鑰
SecItemDelete((__bridge CFDictionaryRef)publicKey);// 先查詢keychain中是否有同tag的,直接刪除
[publicKey setObject:data forKey:(__bridge id)kSecValueData];//設(shè)置keychain的寫入字段的類型kSecValueData
[publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)
kSecAttrKeyClass];//設(shè)置加密密鑰類kSecAttrKeyClassPublic,kSecAttrKeyClassPrivate或者kSecAttrKeyClassSymmetric,這里是公鑰
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
kSecReturnPersistentRef];//設(shè)置是否返回持久型實例(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];//設(shè)置返回實例(SecKeychainItemRef, SecKeyRef, SecCertificateRef, SecIdentityRef, or CFDataRef)
[publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];// 這里其實原來已經(jīng)添加過...
//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.reibang.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開頭的,或者說第一個字節(jié)一定是30(16進制)
if (c_key[idx++] != 0x30) return(nil);
//2.第二個字節(jié)一定是81或者82,81代表長度用1byte表示惧互,82代表長度用2byte表示(此字節(jié)部分tag后不存在
if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
else idx++;
//3. 默認使用PKCS1填充格式,使用公共的頭部數(shù)據(jù)填充: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值,就是最后的內(nèi)容
return ([NSData dataWithBytes:&c_key[idx] length:len - idx]);
}
/**
使用SecKeyRef對象加密核心方法
@param data 待加密二進制數(shù)據(jù)
@param keyRef 密鑰SecKeyRef對象
@return RSA加密以后二進制數(shù)據(jù)
*/
+ (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<srclen; idx+=src_block_size){
//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
size_t data_len = srclen - idx;
if(data_len > 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<srclen; idx+=src_block_size){
//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
size_t data_len = srclen - idx;
if(data_len > 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
只有公鑰的模n和公開冪e
當只有模n和公開冪e的時候,如果后臺使用的JAVA,比較常見的情況是傳遞一個xml,內(nèi)部包含公鑰的長度,模n,以及冪e(有可能是base64的string,或者16進制data)下面的就有一個通用格式和一個實例:
<BitStrength>1024</BitStrength>
<RSAKeyValue>
<Modulus>xxxxxxxxxxxxxxxxxxxxx</Modulus>
<Exponent>xxxx</Exponent>
</RSAKeyValue>
<RSAKeyValue>
<Modulus>yOTe0L1/NcbXdZYwliS82MiTE8VD5WD23S4RDsdbJOFzCLbsyb4d+K1M5fC+xDfCkji1zQjPiiiToZ7JSj/2ww==</Modulus>
<Exponent>AWAB</Exponent>
</RSAKeyValue>
iOS系統(tǒng)的庫不支持直接使用模n和冪e直接對數(shù)據(jù)進行加密.但是有大神開源了這個庫SCZ-BasicEncodingRules-iOS.這個庫的作用是通過已知的RSA的公鑰的modulus和exponent,創(chuàng)建一個RSA的public key.下面是調(diào)用方法:
//注意使用這個庫之前需要將base64的string轉(zhuǎn)化成nsdata數(shù)據(jù)
// pubKeyModData 模n的二進制表示
// pubKeyExpData 冪e的二進制表示
NSMutableArray *testArray = [[NSMutableArray alloc] init];
[testArray addObject:pubKeyModData];
[testArray addObject:pubKeyExpData];
NSData *testPubKey = [testArray berData];
然后,將剛剛生成的publickey data寫入keychain中,其他步驟見上節(jié):
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
或者我們可以創(chuàng)建一個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開源庫包括系統(tǒng)API以及OpenSSL完成
QuickRSA,可以通過iOS的系統(tǒng)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
類,進行如下類型的轉(zhuǎn)換:
- 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轉(zhuǎn)化成PEM 格式的 pubic key的工具:
https://superdry.apphb.com/tools/online-rsa-key-converter