我需要使用公钥将用户密码加密为 base64 字符串。

公钥是一个 NSString。

像这样的东西:



我如何从中制作 SecKeyRef ?

我找到了一个教程 here

但我无法让它工作,因为 SecCertificateCreateWithData 总是返回 nil。

这是我的代码

NSData* data = [NSString base64DataFromString:PUBLIC_KEY];
SecCertificateRef   cert    = NULL;
SecPolicyRef        policy  = NULL;

cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)(data));
policy = SecPolicyCreateBasicX509();

OSStatus        status      = noErr;
SecKeyRef       *publicKey  = NULL;
SecTrustRef     trust       = NULL;
SecTrustResultType  trustType   = kSecTrustResultInvalid;

if (cert != NULL){
    SecCertificateRef   certArray[1] = {cert};
    CFArrayRef certs = CFArrayCreate(kCFAllocatorDefault, (void *)certArray, 1, NULL);
    status = SecTrustCreateWithCertificates(certs, policy, &trust);

    if (status == errSecSuccess){
        status = SecTrustEvaluate(trust, &trustType);

        // Evaulate the trust.
        switch (trustType) {
            case kSecTrustResultInvalid:
            case kSecTrustResultConfirm:
            case kSecTrustResultDeny:
            case kSecTrustResultUnspecified:
            case kSecTrustResultFatalTrustFailure:
            case kSecTrustResultOtherError:
                break;
            case kSecTrustResultRecoverableTrustFailure:
                *publicKey = SecTrustCopyPublicKey(trust);
                break;
            case kSecTrustResultProceed:
                *publicKey = SecTrustCopyPublicKey(trust);
                break;
        }

    }
} else {
    NSLog(@"CERT == NULL");
}

if (publicKey == NULL) {
    NSLog(@"PUBLIC KEY == NULL");
}

SecKeyRef 始终为零,因为证书也为零。
请帮我。

最佳答案

你不能只传递关键数据。您必须通过由您的 key 签名的证书才能从证书中提取 key 。请参阅 this answersimilar question

关于来自 NSString 的 iOS SecKeyRef,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26119952/

10-08 20:56