ios - 一个函数 swift 给出多个结果

标签 ios objective-c c swift openssl

我在 objective-C 中有一个方法,我从 swift 调用它。它在 swift 2 中运行良好,但在 swift 3 中行为发生了变化。它给了我 3 个不同的结果,即使我发送了相同的参数。

有时它找不到 pfile,有时它在 pin 检查时失败,有时工作正常并给我 x509。

char* ParsePKCS12(unsigned char* pkcs12_path, unsigned char * pin) {
printf("PARSE PATH: %s\n", pkcs12_path);
printf("PASSWORD: %s\n", pin);

NSString *pfile = [NSString stringWithUTF8String:pkcs12_path];
FILE *fp;
PKCS12 *p12;
EVP_PKEY *pkey;
X509 *cert;

BIO *databio = BIO_new(BIO_s_mem());
STACK_OF(X509) *ca = NULL;

if([[NSFileManager defaultManager] fileExistsAtPath:pfile]) {
    NSLog(@"ok, pfile exists!");
} else {
    NSLog(@"error, pfile does not exists!");
    return "-1";
}
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
fp = fopen([pfile UTF8String], "rb");
p12 = d2i_PKCS12_fp(fp, NULL);
fclose (fp);
if (!p12) {
    fprintf(stderr, "Error reading PKCS#12 file\n");
    ERR_print_errors_fp(stderr);
    return "-1";
}

if (!PKCS12_parse(p12, (const char *)pin, &pkey, &cert, &ca)) { //Error at parsing or pin error
    fprintf(stderr, "Error parsing PKCS#12 file\n");
    ERR_print_errors_fp(stderr);
    ERR_print_errors(databio);
    return "-1";
}

BIO *bio = NULL;
char *pem = NULL;

if (NULL == cert) {
    //return NULL;
    return "-1";
}

bio = BIO_new(BIO_s_mem());
if (NULL == bio) {
    return "-1";
}

if (0 == PEM_write_bio_X509(bio, cert)) {
    BIO_free(bio);
    //return NULL;
}

pem = (char *) malloc(bio->num_write + 1);
if (NULL == pem) {
    BIO_free(bio);
    return "-1";
}

memset(pem, 0, bio->num_write + 1);
BIO_read(bio, pem, bio->num_write);
BIO_free(bio);

PKCS12_free(p12);

return pem;
}

我像这样快速调用这段代码:

self.x509 = String(cString:ParsePKCS12(UnsafeMutablePointer<UInt8>(mutating: self.path),
                                           UnsafeMutablePointer<UInt8>(mutating: "123456"))!)

最佳答案

你的电话

self.x509 = String(cString:ParsePKCS12(UnsafeMutablePointer<UInt8>(mutating: self.path),
                                           UnsafeMutablePointer<UInt8>(mutating: "123456"))!)

不能可靠地工作,因为在两者中

UnsafeMutablePointer<UInt8>(mutating: someSwiftString)

调用,编译器创建一个临时的 C 字符串表示 Swift 字符串并将其传递给函数。但是那个C弦 仅在 UnsafeMutablePointer 构造函数返回之前有效,这意味着第二个 字符串转换可以覆盖第一个,或任何其他未定义的 行为。

最简单的解决方案是将 C 函数更改为 采用常量 C 字符串(并使用默认符号):

char* ParsePKCS12(const char * pkcs12_path, const char * pin)

然后你可以简单地称它为

self.x509 = String(cString: ParsePKCS12(self.path, "123456"))

并且编译器创建临时的 C 字符串,这些字符串在 ParsePKCS12() 的调用。

关于ios - 一个函数 swift 给出多个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40171285/

相关文章:

objective-c - react 性 NSMutableDictionary?

objective-c - NSString 上的 stringWithFormat 与 initWithFormat

c - 在c中验证字符串

c - C 中的 malloc 代码

c - CPU乱序影响测试程序

ios - 未调用 MKMapView MKPointAnnotation 点击​​事件

ios - didUpdateLocations 未被调用

ios - 我需要检测某个 View 上的触摸

ios - Azure 通知中心与 APNS

iphone - 如何检查某个功能是否适用于特定的 iOS 版本?