2017-07-19 50 views
0

我基本上是按照這個guide生成一個私鑰,複製公鑰,然後加密一條消息。但是,它給了我錯誤(OSStatus錯誤-67712 - CSSM異常:-2147415791 CSSMERR_CSP_INVALID_KEY_REFERENCE)。OSX生成的密鑰無法加密(SecKeyCreateRandomKey&SecKeyCreateEncryptedData)

最初,我以爲我錯誤地設置了屬性。但是,如果我通過SecKeyGeneratePair()函數創建公鑰(具有相同的屬性),則一切正常。這是不是很奇怪?

void TestEncryptDecrpt() { 
    OSStatus status; 
    NSData* tag = [@"com.example.keys.mykey" dataUsingEncoding:NSUTF8StringEncoding]; 
    NSDictionary* attributes = 
    @{ (id)kSecAttrKeyType:    (id)kSecAttrKeyTypeRSA, 
     (id)kSecAttrKeySizeInBits:   @1024, 
     (id)kSecPrivateKeyAttrs: 
      @{ (id)kSecAttrIsPermanent: @YES, 
       (id)kSecAttrApplicationTag: tag, 
       }, 
     }; 

    CFErrorRef error = NULL; 
    SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes, &error);   
    SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey); 


    // *** it will work if I generate the key by SecKeyGeneratePair *** 
    // status = SecKeyGeneratePair((__bridge CFDictionaryRef)attributes, &publicKey, &privateKey); 


    // start encrypt and decrypt a message 
    static char const kMessage[] = "This is a secret!\n";   
    SecKeyAlgorithm algorithm = kSecKeyAlgorithmRSAEncryptionRaw;   
    BOOL canEncrypt = SecKeyIsAlgorithmSupported(publicKey, kSecKeyOperationTypeEncrypt, algorithm); 
    NSData* plainData = [NSData dataWithBytes:kMessage length:sizeof(kMessage)]; 
    canEncrypt &= ([plainData length] < (SecKeyGetBlockSize(publicKey)-130)); 

    NSData* cipherText = nil; 
    if (canEncrypt) { 
     CFErrorRef error = NULL; 
     cipherText = (NSData*)CFBridgingRelease(SecKeyCreateEncryptedData(publicKey, algorithm, (__bridge CFDataRef)plainData, &error)); 
     if (!cipherText) { 
      NSError *err = CFBridgingRelease(error); // ARC takes ownership 
      // Handle the error. . . 
      NSLog(@"error = %@, %@", [err userInfo], [err localizedDescription]); 
     } 
    } 
} 
+0

不幸的是,你的鏈接已經死亡。蘋果公司的文件並不像他們應該那樣永久:/ –

回答

1

問題解決了。您還需要公鑰設置中的「kSecAttrIsPermanent」屬性。

不知道爲什麼這在示例中沒有提到。