iOS 不僅提供了RSA加解密,簽名驗(yàn)簽的功能,同時(shí)還提供了生成密鑰對的方法。
SecKeyEncrypt (解密)
SecKeyDecrypt(解密)
SecKeyGeneratePair(生成密鑰對)
關(guān)于分段加密
因?yàn)镽SA是需要分段加密的,每一段的長度不能大于密鑰的長度SecKeyGetBlockSize(keyRef),一般為128(1024bit的密鑰)字節(jié)。
但是由于RSA加密會(huì)設(shè)置填充模式,常用的模式為RSA_PKCS1_PADDING,在這種模式下,每次加密的明文長度需要再減少11個(gè)字節(jié),所以在分段的時(shí)候每段的長度為 128 - 11 = 117 ;
size_t src_block_size = block_size - 11;
iOS 原生生成RSA密鑰對的類型為SecKeyRef類型,也可以將 SecKeyRef 類型轉(zhuǎn)換為NSData。這里生成的數(shù)據(jù)只包含了公鑰的信息,不是標(biāo)準(zhǔn)的PEM格式的文件,如果需要PEM格式需要添加PEM頭信息
- (NSData *)getKeyBitsWithKeyIdentifier:(NSString *)keyIdentifier {
if (!keyIdentifier) {
return nil;
}
NSData *keyBits = nil;
OSStatus sanityCheck = noErr;
NSData * peerTag = [keyIdentifier dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary * queryAttributes = [[NSMutableDictionary alloc] init];
[queryAttributes setObject:(id)kSecClassKey forKey:(id)kSecClass];
[queryAttributes setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[queryAttributes setObject:peerTag forKey:(id)kSecAttrApplicationTag];
[queryAttributes setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData];
CFTypeRef result = NULL;
sanityCheck = SecItemCopyMatching((CFDictionaryRef) queryAttributes, &result);
if (sanityCheck == noErr || sanityCheck == errSecDuplicateItem) {
keyBits = CFBridgingRelease(result);
return keyBits;
}
return nil;
}
在設(shè)置queryAttributes 的參數(shù)中,下面這行
[queryAttributes setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData];
key有三種類型可選
kSecReturnData
kSecReturnRef
kSecReturnPersistentRef
如果選kSecReturnPersistentRef類型,可用下面的方法轉(zhuǎn)換
- (SecKeyRef)getKeyRefWithPersistentKeyRef:(CFTypeRef)persistentRef {
OSStatus sanityCheck = noErr;
SecKeyRef keyRef = NULL;
if (persistentRef == NULL) {
//@"persistentRef object cannot be NULL."
return nil;
}
NSMutableDictionary * queryKey = [[NSMutableDictionary alloc] init];
// Set the SecKeyRef query dictionary.
[queryKey setObject:(__bridge id)persistentRef forKey:(id)kSecValuePersistentRef];
[queryKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef];
// Get the persistent key reference.
sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryKey, (CFTypeRef *)&keyRef);
return keyRef;
}