gpt4 book ai didi

ios - OSX 生成的 key 无法加密(SecKeyCreateRandomKey 和 SecKeyCreateEncryptedData)

转载 作者:行者123 更新时间:2023-11-29 00:16:37 25 4
gpt4 key购买 nike

我基本上是按照这个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]);
}
}
}

最佳答案

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

不确定为什么示例中没有提到这一点。

关于ios - OSX 生成的 key 无法加密(SecKeyCreateRandomKey 和 SecKeyCreateEncryptedData),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45181756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com