0

我基本上是按照本指南生成私钥,复制公钥,然后加密消息。但是,它给了我错误(OSStatus 错误 -67712 - CSSM 异常:-2147415791 CSSMERR_CSP_INVALID_KEY_REFERENCE)。

最初,我以为我错误地设置了属性。但是,如果我通过 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]);
        }
    }
}
4

1 回答 1

1

问题解决了。您还需要公钥设置中的“kSecAttrIsPermanent”属性。

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

于 2017-07-19T06:11:22.073 回答