下面是我的代码,它在 iOS 9 之前都可以正常工作。
- (NSData *)encryptWithDataPublicKey:(NSString*)data keyTag:(NSString*)tag
{
SecKeyRef publicKey = NULL;
NSData *publicTag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
NSMutableDictionary *queryPublicKey =
[[NSMutableDictionary alloc] init];
[queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
OSStatus status = SecItemCopyMatching
((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKey);
NSData *encodedData = nil;
if (status == noErr && publicKey) {
NSData *dataToEncrypt = [data dataUsingEncoding:NSUTF8StringEncoding];
encodedData = [self encryptData:dataToEncrypt withKeyRef:publicKey];
CFRelease(publicKey);
}
return encodedData;
}
这种方法在 iOS 9.x 之前可以正常工作,但是今天我将 XCode 更新到 8 并在 iOS 10 设备上运行。应用程序在
CFRelease(publicKey)处崩溃。
在下面崩溃之前是来自控制台的日志。
无法加载任何 Objective-C 类信息。这将显着降低可用类型信息的质量
无法准确解决问题。
当我启用 Zombie 并重现崩溃时。以下是来自控制台的日志。
*** -[Not A Type release]:消息发送到释放的实例 0x170225880
提前致谢。
我得到了问题。有一个内部方法 encodedData = [self encryptData:dataToEncrypt withKeyRef:publicKey];
SecKeyRef 对象被释放的地方。
但我想知道这在 iOS9 之前是如何工作的???????
-(NSData *)encryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
const uint8_t *srcbuf = (const uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
void *outbuf = malloc(block_size);
size_t src_block_size = block_size - 11;
NSMutableData *ret = [[NSMutableData alloc] init];
for(int idx=0; idx<srclen; idx+=src_block_size){
size_t data_len = srclen - idx;
if(data_len > src_block_size){
data_len = src_block_size;
}
size_t outlen = block_size;
OSStatus status = noErr;
status = SecKeyEncrypt(keyRef,
kSecPaddingPKCS1,
srcbuf + idx,
data_len,
outbuf,
&outlen
);
if (status != 0) {
ret = nil;
break;
}else{
[ret appendBytes:outbuf length:outlen];
}
}
free(outbuf);
CFRelease(keyRef);
return ret;
}