【问题标题】:OSX Generated key can't encrypt (SecKeyCreateRandomKey & SecKeyCreateEncryptedData)OSX 生成的密钥无法加密(SecKeyCreateRandomKey & SecKeyCreateEncryptedData)
【发布时间】:2017-12-24 04:56:03
【问题描述】:

我基本上是按照guide 生成私钥,复制公钥,然后加密消息。但是,它给了我错误(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]);
        }
    }
}

【问题讨论】:

  • 很遗憾,您的链接已失效。 Apple 的文档并不像他们应该的那样永久:/

标签: ios objective-c macos encryption seckeyref


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 2015-09-13
    • 1970-01-01
    • 2015-07-27
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多