2013-06-26 156 views
1

我想每次应用相同的种子时生成相同的非对称密钥对。iOS生成RSA非随机密钥对?

我已经使用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]; 
} 
+0

难道你不能只存储钥匙链中的私钥,并从钥匙串中检索它(如果存在)?能够两次生成相同的私钥似乎很奇怪。如果您可以随意生成相同的密钥,则不是很私密。 – gnasher729

回答

2

“公共和私有标记”您正在设置是简单的,你可以搜索以后使用SecItemCopyMatching如果您存储在钥匙链上的密钥对标识符。

不幸的是,您不能使用SecKeyGeneratePairSecKeyGeneratePairAsync来设置不对称密钥对的“种子”值。您将始终获得“随机生成”密钥对。

如果您必须这样做,您将不得不查看其他提供该功能的库。

+0

你能为iOS提供任何图书馆建议吗? 谢谢 – user2524377

+0

@ user2524377,我建议先看看OpenSSL。 –