gpt4 book ai didi

ios - 从 NSString 创建KeychainValue

转载 作者:可可西里 更新时间:2023-11-01 05:41:19 28 4
gpt4 key购买 nike

我正在尝试将证书添加到钥匙串(keychain)。我看到有几篇文章是从一个文件创建的,但我想从 NSString 创建一个。

我的 NSString 在 RSA - 64base 上,就像:

-----BEGIN CERTIFICATE-----
MIIDoDCCAoigAwIBAgIJAL8qgXMVVVhPMA0GCSqGSIb3DQEBBQUAMGwxCzAJBgNVBAYTAkJSMRIw
...
FT70at8bty9ocDaXuI3j6mfw2SI=
-----END CERTIFICATE-----

我正在尝试做这样的事情:

+ (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier {
NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init];

[searchDictionary setObject:(__bridge id)kSecClassCertificate forKey:(__bridge id)kSecClass];

NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
[searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrGeneric];
[searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrAccount];
[searchDictionary setObject:SERVICE_NAME forKey:(__bridge id)kSecAttrService];
return searchDictionary;
}


+ (BOOL)createKeychainValue:(NSString *)certificado forIdentifier:(NSString *)identifier {
NSMutableDictionary *dictionary = [self newSearchDictionary:identifier];

NSData *certificadoData = [certificado dataUsingEncoding:NSUTF8StringEncoding];
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certificadoData);

[dictionary setObject:(__bridge id)(cert) forKey:(__bridge id<NSCopying>)(kSecValueRef)];

OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL);

CFRelease(cert);

if (status == errSecSuccess) {
return YES;
}
return NO;
}

但是返回的证书为零。可能是因为我的证书是 PEM 而我需要 DER。我该如何转换?我在我的项目中使用 openssl。

最佳答案

对我有用并创建 SecCertificateRef 的函数是:

+ (NSData *)derFromPem:(NSString *)pem {

BIO *certBio = BIO_new(BIO_s_mem());
BIO_write(certBio, [pem UTF8String], strlen([pem UTF8String]));
X509 *x = PEM_read_bio_X509(certBio,NULL,0,NULL);
BIO *outBio = BIO_new(BIO_s_mem());
i2d_X509_bio(outBio, x);

int len = BIO_pending(outBio);
char *out = calloc(len + 1, 1);
int i = BIO_read(outBio, out, len);

return [NSData dataWithBytes:out length:i];
}

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

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