2012-04-08 5 views
6

seguito di Apple codice di esempio in: http://developer.apple.com/library/ios/#documentation/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.htmlGenera coppia di chiavi su iPhone e di stampa per accedere come NSString

sono in grado di generare con successo coppia di chiavi con il frammento di codice di seguito, ma in grado di stampare le chiavi ...

La funzione SecKeyGeneratePair() - restituisce le chiavi come tipo SecKeyRef.

Non ho idea di come gestire questo tipo, capisco che questa è la rappresentazione portachiavi, ma come posso effettivamente visualizzare la coppia di chiavi come NSString ?? Più specificamente, come convertire SecKeyRef in 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

Non in grado di generare chiavi coppia ... E sta dando valore per lo stato 'OSStatus' ** - 34018 ** – Sujay

risposta

7

È possibile utilizzare SecItemCopyMatching per ottenere NSData di chiave. Controlla il metodo getPublicKeyBits in Apple's CryptoExercise, implementa esattamente ciò di cui hai bisogno.

Quindi è possibile convertire NSData in una stringa. Forse, la codifica Base64 soddisferà le tue esigenze. Here puoi trovare il codice di codifica/decodifica Base64 per iPhone. In alternativa, questo answer potrebbe anche essere utile per la codifica Base64.

+0

grazie, io uso getPublicKeyBits e lo faccio r eceive il valore come NSData, c'è qualcosa di strano però, quando creo la keypair, specifico kSecAttrKeySizeInBits = 1024, ma la dimensione NSData (ricevuta da getPublicKeyBits) è 140 byte (invece del previsto 128) qualche idea del perché ?? –

+1

Ciò è probabilmente dovuto al formato utilizzato per memorizzare le chiavi. Non sono sicuro di quale sia la ragione per cui stai stampando le chiavi. Checkout [this] (http://blog.wingsofhermes.org/?p=42) e [this] (http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios /) collegamenti che discutono i modi per lavorare con le chiavi iOS. – tenorsax

+0

Posso ottenere NSData e generare un utilizzo NSString: '[data base64EncodedDataWithOptions: NSDataBase64Encoding64CharacterLineLength]; [[NSString alloc] initWithData: codifica base64Data: NSUTF8StringEncoding]; '. Ma non è possibile utilizzare questo NSString per crittografare. 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]); 
} 

È possibile trovare tutto il codice qui https://github.com/ozgurshn/EncryptionForiOS

2

È possibile utilizzare 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 
} 

rapida 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

Non funziona ancora con Swift 3. –

+0

aggiunto codice per swift 3 – phnmnn