3
我想使用iPhone的PKI庫來加密一個短字符串(12345678),但我不斷收到錯誤-9809(即errSSLCrypto),只要我嘗試使用SecKeyEncrypt。 SecureTransport.h頭文件將此錯誤簡單描述爲「潛在的加密錯誤」,這並不十分有意義。iPhone公鑰加密SecKeyEncrypt返回錯誤9809(errSSLCrypto)
我的代碼如下:
- (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;
}
不要緊,我用什麼填充,他們都給予了同樣的錯誤。公鑰是從我的客戶提供的證書中派生出來的,我已經檢查確認密鑰是有效的。我做錯了什麼,如何正確使用該功能?
Thax爲您的功能幫助我加密。但是我在加密時會在加密的字符串中出現奇怪的字符。任何想法 ? –
提出一個新問題併發布您的代碼示例,並將該鏈接添加爲註釋。我會看看它。 – futureelite7
這裏m_oCert是什麼? – HPM