iOS 原生RSA加解密 及生成密钥对

iOS 不仅提供了RSA加解密,签名验签的功能,同时还提供了生成密钥对的方法。

SecKeyEncrypt (解密)
SecKeyDecrypt(解密)
SecKeyGeneratePair(生成密钥对)

关于分段加密
因为RSA是需要分段加密的,每一段的长度不能大于密钥的长度SecKeyGetBlockSize(keyRef),一般为128(1024bit的密钥)字节。
但是由于RSA加密会设置填充模式,常用的模式为RSA_PKCS1_PADDING,在这种模式下,每次加密的明文长度需要再减少11个字节,所以在分段的时候每段的长度为 128 - 11 = 117 ;

size_t src_block_size = block_size - 11;

iOS 原生生成RSA密钥对的类型为SecKeyRef类型,也可以将 SecKeyRef 类型转换为NSData。这里生成的数据只包含了公钥的信息,不是标准的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;
}

在设置queryAttributes 的参数中,下面这行

[queryAttributes setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData];

key有三种类型可选

kSecReturnData
kSecReturnRef
kSecReturnPersistentRef

如果选kSecReturnPersistentRef类型,可用下面的方法转换

- (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;
}

demo一份
官方代码地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 嘟哝嘟哝:最近接到一个任务:在客户端动态生成RSA密钥对,然后向服务器发送这个密钥对中的公钥字符串,由服务器进行公...
    TimmyR阅读 8,129评论 19 21
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,253评论 19 139
  • 本文主要介绍移动端的加解密算法的分类、其优缺点特性及应用,帮助读者由浅入深地了解和选择加解密算法。文中会包含算法的...
    苹果粉阅读 11,623评论 5 29
  • 海洋临河里门市切位信息(经理带队) 2月25日 腾冲瑞丽芒市第六套 双飞5日 (19+1精品小团)原件3560元/...
    2173a787ca3b阅读 352评论 0 0
  • 2017年4月27日 1.感恩爸妈帮助照顾孩子。 2.感恩儿子让我享受到幸福。 3.感恩先生为家努力付出。 4.感...
    冯梓源阅读 156评论 0 0