iOS 生成 RSA 非随机密钥对?
Posted
技术标签:
【中文标题】iOS 生成 RSA 非随机密钥对?【英文标题】:iOS Generate RSA non Random key pair? 【发布时间】:2013-06-23 16:59:36 【问题描述】:我想在每次应用相同种子时生成相同的非对称密钥对。
我使用 ios RSA 加密练习来生成 RSA 非对称密钥对。 我也每次都使用相同的种子。 (公共和私人标签) 但是,每次生成时我都会收到不同的密钥。
- (void)generateKeyPair:(NSUInteger)keySize
OSStatus sanityCheck = noErr;
publicKeyRef = NULL;
privateKeyRef = NULL;
LOGGING_FACILITY1( keySize == 512 || keySize == 1024 || keySize == 2048, @"%d is an invalid and unsupported key size.", keySize );
// First delete current keys.
[self deleteAsymmetricKeys];
// Container dictionaries.
NSMutableDictionary * privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * keyPairAttr = [[NSMutableDictionary alloc] init];
// Set top level dictionary for the keypair.
[keyPairAttr setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithUnsignedInteger:keySize] forKey:(id)kSecAttrKeySizeInBits];
// Set the private key dictionary.
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrIsPermanent];
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrCanEncrypt];
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrCanDecrypt];
[privateKeyAttr setObject:privateTag forKey:(id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set the public key dictionary.
[publicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag forKey:(id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set attributes to top level dictionary.
[keyPairAttr setObject:privateKeyAttr forKey:(id)kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr forKey:(id)kSecPublicKeyAttrs];
// SecKeyGeneratePair returns the SecKeyRefs just for educational purposes.
sanityCheck = SecKeyGeneratePair((CFDictionaryRef)keyPairAttr, &publicKeyRef, &privateKeyRef);
LOGGING_FACILITY( sanityCheck == noErr && publicKeyRef != NULL && privateKeyRef != NULL, @"Something really bad went wrong with generating the key pair." );
NSLog(@"getPublicKeyBits: %@", [self getPublicKeyBits]);
NSLog(@"getPublicKeyExp: %@", [self getPublicKeyExp]);
NSLog(@"getPublicKeyMod: %@", [self getPublicKeyMod]);
// NSLog(@"keyPairAttr: %@" , keyPairAttr);
[privateKeyAttr release];
[publicKeyAttr release];
[keyPairAttr release];
【问题讨论】:
你不能只将私钥存储在钥匙链中,如果存在的话,从钥匙链中检索它吗?能够两次生成相同的私钥似乎很奇怪。如果您可以随意生成相同的密钥,它就不是很私密。 【参考方案1】:您设置的“公共和私有标签”只是标识符,如果您将密钥对存储在密钥链中,您可以稍后使用SecItemCopyMatching
搜索。
很遗憾,您无法使用SecKeyGeneratePair
或SecKeyGeneratePairAsync
为非对称密钥对设置“种子”值。您将始终获得“随机生成”的密钥对。
如果您必须这样做,您将不得不查看提供该功能的其他库。
【讨论】:
您能否推荐任何适用于 iOS 的库。谢谢 @user2524377,我建议先看看 OpenSSL。以上是关于iOS 生成 RSA 非随机密钥对?的主要内容,如果未能解决你的问题,请参考以下文章