首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSString到SecKeyRef

NSString到SecKeyRef
EN

Stack Overflow用户
提问于 2014-07-07 22:05:00
回答 1查看 2.2K关注 0票数 1

我使用的代码是:https://stackoverflow.com/a/19221754/849616,但是并不是所有的东西对我来说都是清晰的。

我想使用公钥NSString *pubKey = "1111"NSString *msg = "0000"进行加密。因此,我正在更新常量:

代码语言:javascript
复制
static const UInt8 publicKeyIdentifier[] = 1111; 
// i want to encrypt only, so private key doesn't matter and I'm not posting it here

在函数testAsymmetricEncryptionAndDecryption中,我更新了:

代码语言:javascript
复制
const char inputString[] = 0000

然而,结果是错误的。publicKeyIdentifier是放置我的密钥串的正确位置吗?如果我的方法是错误的,我应该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2014-09-17 22:04:27

好吧,这个问题是错误的。我甚至不应该尝试将它转换为NSString。您应该将这两个键都放到您的项目中,并使用类似于:

代码语言:javascript
复制
- (SecKeyRef)getPrivateKeyRef {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"rsaPrivate" ofType:@"p12"];
    NSData *p12Data = [NSData dataWithContentsOfFile:resourcePath];

    NSMutableDictionary *options = [[NSMutableDictionary alloc] init];

    SecKeyRef privateKeyRef = NULL;

    //change to the actual password you used here
    [options setObject:@"!@#EWQ" forKey:(__bridge id)kSecImportExportPassphrase];
    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    OSStatus securityError = SecPKCS12Import((__bridge CFDataRef)p12Data, (__bridge CFDictionaryRef)options, &items);

    if (securityError == noErr && CFArrayGetCount(items) > 0) {
        CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
        SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);

        securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
        if (securityError != noErr) {
            privateKeyRef = NULL;
        }
    }

    CFRelease(items);
    return privateKeyRef;
}

- (SecKeyRef)getPublicKeyRef {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"rsaCert" ofType:@"der"];
    NSData *certData = [NSData dataWithContentsOfFile:resourcePath];
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);
    SecKeyRef key = NULL;
    SecTrustRef trust = NULL;
    SecPolicyRef policy = NULL;

    if (cert != NULL) {
        policy = SecPolicyCreateBasicX509();
        if (policy) {
            if (SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) {
                SecTrustResultType result;
                if (SecTrustEvaluate(trust, &result) == noErr) {
                    key = SecTrustCopyPublicKey(trust);
                }
            }
        }
    }
    if (policy) CFRelease(policy);
    if (trust) CFRelease(trust);
    if (cert) CFRelease(cert);
    return key;
}

这不是我自己写的(只是修改过的),大部分都是抄袭的,但我真的不知道是从哪里来的--某个开源社区。不过,还是要感谢写这篇文章的人。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24612507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档