2017-07-19 229 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”属性。

不知道为什么这在示例中没有提到。