gpt4 book ai didi

ios - NSString 到 SecKeyRef

转载 作者:行者123 更新时间:2023-11-29 12:42:06 25 4
gpt4 key购买 nike

我正在使用此代码:https://stackoverflow.com/a/19221754/849616 ,但对我来说并非一切都清楚。

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

static const UInt8 publicKeyIdentifier[] = 1111; 
// i want to encrypt only, so private key doesn't matter and I'm not posting it here

在函数 testAsymmetricEncryptionAndDecryption 中我更新了:

const char inputString[] = 0000

但是结果是错误的。 publicKeyIdentifier 是放置我的 key 字符串的正确位置吗?如果我的方法不对,我该怎么办?

最佳答案

这个问题错了。我什至不应该尝试将它转换为 NSString。您应该将两个 key 都放入您的项目并使用类似的东西:

- (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;
}

我并没有完全自己写(只是修改),它大部分是复制的,但我真的不知道来自哪里 - 一些开源社区。尽管如此,还是要感谢编写它的人。

关于ios - NSString 到 SecKeyRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24612507/

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