我正在尝试使用iPhone的PKI库加密短字符串(12345678),但每当我尝试使用SecKeyEncrypt时,我都会收到错误-9809(即errSSLCrypto)。 SecureTransport.h头文件将此错误描述为“基础加密错误”,这不是很有意义。
我的代码如下:
- (NSData *)encryptDataWithPublicKey:(NSString *)plainText {
OSStatus result = -1;
NSData *plainTextData = [plainText dataUsingEncoding:NSASCIIStringEncoding];
size_t plainTextLength = [plainTextData length];
SecTrustRef trustRef;
SecTrustResultType trustResult;
SecPolicyRef policy = SecPolicyCreateBasicX509();
result = SecTrustCreateWithCertificates(m_oCert, policy, &trustRef);
if (result != errSecSuccess) {
NSLog(@"Trust create failed with code: %d",result);
return nil;
}
result = SecTrustEvaluate(trustRef, &trustResult);
if (result != errSecSuccess) {
NSLog(@"Trust eval failed with code: %d",result);
CFRelease(trustRef);
return nil;
}
SecKeyRef publicKey = SecTrustCopyPublicKey(trustRef);
uint8_t *cipherTextBuf = NULL;
size_t cipherTextLen = 0;
size_t keyBlockSize = SecKeyGetBlockSize(publicKey);
int maxInputSize = keyBlockSize - 11; //If using PKCS1 Padding, else keyBlockSize
if (plainTextLength > maxInputSize) {
//Fail
NSLog(@"Data size is larger than max permitted!");
CFRelease(trustRef);
CFRelease(publicKey);
CFRelease(policy);
return nil;
}
cipherTextBuf = malloc(sizeof(uint8_t)*keyBlockSize);
memset(cipherTextBuf,0,keyBlockSize);
//result = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, plainTextBuf, plainTextLength, cipherTextBuf, &cipherTextLen);
result = SecKeyEncrypt(publicKey, kSecPaddingNone, (const uint8_t *)[plainTextData bytes], plainTextLength, cipherTextBuf, &cipherTextLen);
NSData *cipherText = nil;
if (result == errSecSuccess) {
cipherText = [NSData dataWithBytes:cipherTextBuf length:cipherTextLen];
} else {
NSLog(@"Error detected: %d",result);
}
free(cipherTextBuf);
cipherTextBuf = NULL;
CFRelease(trustRef);
CFRelease(publicKey);
CFRelease(policy);
return cipherText;
}
使用什么填充并不重要,它们都给出了相同的错误。公钥来自我的客户提供的证书,我已经检查以确保密钥有效。我做错了什么以及如何正确使用该功能?
答案 0 :(得分:7)
使用SecKeyEncrypt时,输入cipherTextLength应该是输出缓冲区的大小。设置
size_t cipherTextLen = keyBlockSize;
解决了这个问题。