iOS安全相關(guān) - iOS中使用RSA加密與解密

通常我們使用iOS的RSA加密或者解密時候,有如下幾種情況(這里只討論使用公鑰加密的情況):

  1. 帶公鑰的證書
  2. PEM的格式public key(base64編碼的PEM格式的公鑰)
  3. DER格式的二進制字符串公鑰
  4. 只有公鑰的模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

參考: https://github.com/ideawu/Objective-C-RSA

只有公鑰的模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

參考

這里還有一個將模n和冪e轉(zhuǎn)化成PEM 格式的 pubic key的工具:
https://superdry.apphb.com/tools/online-rsa-key-converter

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市酪我,隨后出現(xiàn)的幾起案子柳击,更是在濱河造成了極大的恐慌峭状,老刑警劉巖负芋,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件散庶,死亡現(xiàn)場離奇詭異不傅,居然都是意外死亡,警方通過查閱死者的電腦和手機泽台,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進店門什荣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人怀酷,你說我怎么就攤上這事稻爬。” “怎么了蜕依?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵桅锄,是天一觀的道長。 經(jīng)常有香客問我样眠,道長友瘤,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任吹缔,我火速辦了婚禮商佑,結(jié)果婚禮上锯茄,老公的妹妹穿的比我還像新娘厢塘。我一直安慰自己,他們只是感情好肌幽,可當我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布晚碾。 她就那樣靜靜地躺著,像睡著了一般喂急。 火紅的嫁衣襯著肌膚如雪格嘁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天廊移,我揣著相機與錄音糕簿,去河邊找鬼。 笑死狡孔,一個胖子當著我的面吹牛懂诗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播苗膝,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼殃恒,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起离唐,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤病附,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后亥鬓,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體完沪,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年嵌戈,在試婚紗的時候發(fā)現(xiàn)自己被綠了丽焊。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡咕别,死狀恐怖技健,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情惰拱,我是刑警寧澤雌贱,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站偿短,受9級特大地震影響欣孤,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜昔逗,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一降传、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧勾怒,春花似錦婆排、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鉴扫,卻和暖如春赞枕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背坪创。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工炕婶, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人莱预。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓柠掂,卻偏偏與公主長得像,于是被迫代替她去往敵國和親锁施。 傳聞我的和親對象是個殘疾皇子陪踩,可洞房花燭夜當晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容