iOS - 从指数+模数创建SecKeyRef

时间:2011-05-09 21:28:18

标签: iphone ios security rsa

我想通过将指数和模数作为私钥来解密iPhone上的RSA编码blob。在Java(使用javax.crypto)中,这可以通过以下代码轻松实现:

// 1) key
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(myModulus, myPublicExponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
Key pubKey = fact.generatePublic(keySpec);

// 2) cypher
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);

// 3) use cypher to decode my block to an output stream

但是使用iPhone安全API,我无法创建SecKeyRef(密钥),除了生成一对或导入证书,我没有/想要。

有没有办法手动创建一个具有模数+指数的密钥?如果是这样,你能告诉我一个怎样的线索吗?

提前致谢

2 个答案:

答案 0 :(得分:1)

你的指数和模数是如何编码的?如果它们位于PKCS#12 blob中,您可以使用SecPKCS12Import()SecIdentityCopyPrivateKey()来实现您想要的效果。

编辑:鉴于您拥有原始密钥,您可能有兴趣查看Apple的-[SecKeyWrapper addPeerPublicKey:keyBits:]示例provided

答案 1 :(得分:1)

我有一个库,可以让你创建二进制数据,以便在模数和指数中导入RSA密钥:

https://github.com/StCredZero/SCZ-BasicEncodingRules-iOS

SCZ-BasicEncodingRules-IOS

实施基本编码规则以启用将RSA密钥导入iOS KeyChain使用指数。代码针对带有ARC的iOS 5。

假设您已经拥有模数和指数 RSA公钥作为名为pubKeyModData和变量的变量中的NSData pubKeyExpData。然后,以下代码将创建包含该RSA的NSData 公钥,然后您可以将其插入iOS或OS X Keychain。

NSMutableArray *testArray = [[NSMutableArray alloc] init];
[testArray addObject:pubKeyModData];
[testArray addObject:pubKeyExpData];
NSData *testPubKey = [testArray berData];

这将允许您使用Apple CryptoExercise示例中的SecKeyWrapper中的addPeerPublicKey:keyBits:方法存储密钥。或者,从低级API的角度来看,您可以使用SecItemAdd()。

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);
相关问题