本文介绍了来自NSString的iOS SecKeyRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用公共密钥将用户密码加密为base64字符串.
I need to encrypt a user password to base64 string using a public key.
公钥是一个NSString.
The public key is a NSString.
类似这样的东西:
如何从中创建SecKeyRef?
How do I make a SecKeyRef from it ?
我找到了一个教程此处
但是我无法使其工作,因为SecCertificateCreateWithData总是返回nil.
But I couldn't make it work because SecCertificateCreateWithData always return 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始终为零,因为证书也为零.请帮助我.
The SecKeyRef is always nil because the cert is nil too.Please help me.
推荐答案
您不能只传递关键数据.您必须通过密钥签名的证书,才能将密钥从证书中拔出.参见.
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.
这篇关于来自NSString的iOS SecKeyRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!