问题
I need to encrypt a user password to base64 string using a public key.
The public key is a NSString.
Something like this:
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgWO7p1AvCaHUeaM6rSczBBAqt mKObHxGW3VgTom2zGwswGj9t/Hr7NdJQCGAiq0ijcW9/oYnM/JobbsyEijHKqIQm OVMsV4JRoG68PEDszH/ebkqWhzu7vG9IQ6VYIkaKHqk7cg+mQ1qFDoigOooFJ2Pf Uzbmg+Z/DuYDuwg+bwIDAQBC"
How do I make a SecKeyRef from it ?
I found a tutorial here
But I couldn't make it work because SecCertificateCreateWithData always return nil.
This is my code
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");
}
The SecKeyRef is always nil because the cert is nil too. Please help me.
回答1:
You can't just pass key data. You have to pass a certificate signed by your key to be able to pull the key out of the certificate. See this answer to a similar question.
来源:https://stackoverflow.com/questions/26119952/ios-seckeyref-from-nsstring