【发布时间】:2015-10-19 11:21:45
【问题描述】:
我正在尝试使用 iOS 上的安全框架通过 RSA 加密一些数据。我想加密一个简单的 base64 编码字符串,如下所示:
NSData *data = [[NSData alloc] initWithBase64EncodedString:@"aGFsbG8=" options:0x0];
NSData *encrypted = [pair encrypt:data];
pair 变量包含对在使用 SecKeyGeneratePair 之前成功生成的私钥和公钥的引用。
加密函数如下所示:
- (NSData *)encrypt:(NSData *)data {
void *buffer = malloc([self blockSize] * sizeof(uint8_t));
memset(buffer, 0x0, [self blockSize]);
size_t ciphertextBufferLength = [data length];
OSStatus res = SecKeyEncrypt([self keyRef], 0x1, [data bytes], [data length], &buffer[0], &ciphertextBufferLength);
NSLog(@"Result of encryption: %d", res);
return [NSData dataWithBytesNoCopy:buffer length:[self blockSize] freeWhenDone:YES];
}
[self blockSize] 的实现相当简单:
- (unsigned long)blockSize {
return SecKeyGetBlockSize(keyRef);
}
我使用以下功能生成我的密钥:
- (BOOL)generateNewKeyPairOfSize:(unsigned int)keySize
{
SecKeyRef privKey = [[self publicKey] keyRef];
SecKeyRef pubKey = [[self publicKey] keyRef];
NSDictionary *privateKeyDict = @{ (__bridge id)kSecAttrIsPermanent : @(YES), (__bridge id)kSecAttrApplicationTag : [[self privateKey] tag] };
NSDictionary *publicKeyDict = @{ (__bridge id)kSecAttrIsPermanent : @(YES), (__bridge id)kSecAttrApplicationTag : [[self publicKey] tag] };
NSDictionary *keyDict = @{ (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeRSA, (__bridge id)kSecAttrKeySizeInBits : @(keySize), (__bridge id)kSecPublicKeyAttrs : publicKeyDict, (__bridge id)kSecPrivateKeyAttrs : privateKeyDict };
OSStatus res = SecKeyGeneratePair((__bridge CFDictionaryRef)keyDict, &privKey, &pubKey);
NSLog(@"Result of generating keys: %d", res);
[[self publicKey] setKeyRef:pubKey];
[[self privateKey] setKeyRef:privKey];
return YES;
}
问题是res 的值是-4,根据文档,意思是errSecUnimplemented。我不确定我在这里做错了什么,因为我需要所有参数。我不确定参数是否有错误以及在哪里。调用[self blockSize] 返回128。
谁能帮我解决这个问题?
【问题讨论】:
-
你能用 SecKeyGeneratePair() 显示你的密钥生成吗?
-
我已经编辑了我的问题并添加了生成密钥的代码。
标签: ios security encryption cryptography rsa