2012-04-08 15 views
6

obserwuję firmy Apple przykładowy kod w: http://developer.apple.com/library/ios/#documentation/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.htmlGenerowanie pary kluczy na iPhone i drukuj zalogować jako NSString

jestem w stanie z powodzeniem generowania pary kluczy z fragmentem kodu poniżej, ale nie można drukować klucze ...

Funkcja SecKeyGeneratePair() - zwraca klucze jako typ SecKeyRef.

Nie mam pojęcia, jak poradzić sobie z tym typem, rozumiem, że jest to reprezentacja keychain, ale w jaki sposób mogę faktycznie wyświetlić klucz-pary jako NSString? Bardziej szczegółowo, jak przekonwertować SecKeyRef na NSString?

static const UInt8 publicKeyIdentifier[] = "com.apple.sample.publickey\0"; 
static const UInt8 privateKeyIdentifier[] = "com.apple.sample.privatekey\0"; 
                  // 1 


- (void)generateKeyPairPlease 
{ 
    OSStatus status = noErr; 
    NSMutableDictionary *privateKeyAttr = [[NSMutableDictionary alloc] init]; 
    NSMutableDictionary *publicKeyAttr = [[NSMutableDictionary alloc] init]; 
    NSMutableDictionary *keyPairAttr = [[NSMutableDictionary alloc] init]; 
                   // 2 

    NSData * publicTag = [NSData dataWithBytes:publicKeyIdentifier 
           length:strlen((const char *)publicKeyIdentifier)]; 
    NSData * privateTag = [NSData dataWithBytes:privateKeyIdentifier 
           length:strlen((const char *)privateKeyIdentifier)]; 
                   // 3 

    SecKeyRef publicKey = NULL; 
    SecKeyRef privateKey = NULL;        // 4 

    [keyPairAttr setObject:(id)kSecAttrKeyTypeRSA 
            forKey:(id)kSecAttrKeyType]; // 5 
    [keyPairAttr setObject:[NSNumber numberWithInt:1024] 
          forKey:(id)kSecAttrKeySizeInBits]; // 6 

    [privateKeyAttr setObject:[NSNumber numberWithBool:YES] 
           forKey:(id)kSecAttrIsPermanent]; // 7 
    [privateKeyAttr setObject:privateTag 
          forKey:(id)kSecAttrApplicationTag]; // 8 

    [publicKeyAttr setObject:[NSNumber numberWithBool:YES] 
           forKey:(id)kSecAttrIsPermanent]; // 9 
    [publicKeyAttr setObject:publicTag 
          forKey:(id)kSecAttrApplicationTag]; // 10 

    [keyPairAttr setObject:privateKeyAttr 
           forKey:(id)kSecPrivateKeyAttrs]; // 11 
    [keyPairAttr setObject:publicKeyAttr 
           forKey:(id)kSecPublicKeyAttrs]; // 12 

    status = SecKeyGeneratePair((CFDictionaryRef)keyPairAttr, 
             &publicKey, &privateKey); // 13 
// error handling... 


    if(privateKeyAttr) [privateKeyAttr release]; 
    if(publicKeyAttr) [publicKeyAttr release]; 
    if(keyPairAttr) [keyPairAttr release]; 
    if(publicKey) CFRelease(publicKey); 
    if(privateKey) CFRelease(privateKey);      // 14 
} 
+0

Nie stanie wygenerować parę kluczy ... To daje wartość dla statusu "OSStatus" ** - 34018 ** – Sujay

Odpowiedz

7

Możesz użyć SecItemCopyMatching, aby pobrać NSData klucza. Sprawdź metodę getPublicKeyBits w Apple's CryptoExercise, implementuje dokładnie to, czego potrzebujesz.

Następnie można przekształcić NSData w ciąg znaków. Być może kodowanie Base64 zaspokoi Twoje potrzeby. Here można znaleźć próbkę kodowania/dekodowania Base64 dla iPhone'a. Alternatywnie ten answer może być również użyteczny do kodowania Base64.

+0

dziękuję, korzystam z getPublicKeyBits i robię r eceive wartość jako NSData, jest coś dziwnego, podczas tworzenia klucza Podaję kSecAttrKeySizeInBits = 1024, ale rozmiar NSData (otrzymany z getPublicKeyBits) wynosi 140 bajtów (zamiast oczekiwanych 128) jakikolwiek pomysł dlaczego ?? –

+1

Jest to prawdopodobnie spowodowane formatem używanym do przechowywania kluczy. Nie jestem pewien, jaki jest powód, dla którego drukujesz klucze. Checkout [this] (http://blog.wingsofhermes.org/?p=42) i [this] (http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios /) linki omawiające sposoby pracy z kluczami iOS. – tenorsax

+0

Mogę pobrać NSData i wygenerować użycie NSString: '[data base64EncodedDataWithOptions: NSDataBase64Encoding64CharacterLineLength]; [[NSString alloc] initWithData: base64Data encoding: NSUTF8StringEncoding]; '. Ale nie można użyć tego NSString do szyfrowania. SOS –

0
-(void)writePublicKeyModAndExp 
{ 
    KeyHelper* keyHelper =[[KeyHelper alloc]init]; 
    NSData* pubkeyData= [keyHelper getPublicKeyBitsWithtag:publicTag]; 

    NSLog(@"pubKey :%@",[pubkeyData base64Encoding]); 

    NSData *modData= [keyHelper getPublicKeyModFromKeyData:pubkeyData]; 
    NSLog(@"modulus :%@",[modData base64Encoding]); 

    NSData *expoData= [keyHelper getPublicKeyExpFromKeyData:pubkeyData]; 
    NSLog(@"exponent :%@",[expoData base64Encoding]); 
} 

można znaleźć cały kod tutaj https://github.com/ozgurshn/EncryptionForiOS

2

Można użyć https://github.com/henrinormak/Heimdall

let localHeimdall = Heimdall(tagPrefix: "com.example") 

if let heimdall = localHeimdall { 
    let publicKeyData = heimdall.X509PublicKey() 
    var publicKeyString = publicKeyData.base64EncodedStringWithOptions(.allZeros) 

    // If you want to make this string URL safe, 
    // you have to remember to do the reverse on the other side later 
    publicKeyString = publicKeyString.stringByReplacingOccurrencesOfString("/", withString: "_") 
    publicKeyString = publicKeyString.stringByReplacingOccurrencesOfString("+", withString: "-") 

    println(publicKeyString) // Something along the lines of "MIGfMA0GCSqGSIb3DQEBAQUAA..." 

    // Data transmission of public key to the other party 
} 

Swift 3:

let localHeimdall = Heimdall(tagPrefix: "com.example") 
if let heimdall = localHeimdall, publicKeyData = heimdall.publicKeyDataX509() { 

    var publicKeyString = publicKeyData.base64EncodedString() 

    // If you want to make this string URL safe, 
    // you have to remember to do the reverse on the other side later 
    publicKeyString = publicKeyString.replacingOccurrences(of: "/", with: "_") 
    publicKeyString = publicKeyString.replacingOccurrences(of: "+", with: "-") 

    println(publicKeyString) // Something along the lines of "MIGfMA0GCSqGSIb3DQEBAQUAA..." 

    // Data transmission of public key to the other party 
} 
+0

To nie działa jeszcze z Swift 3. –

+0

dodano kod dla Swift 3 – phnmnn

Powiązane problemy