2015-06-12 64 views
1

我需要在Mac上對數據進行數字簽名,然後在iOS上驗證它。所以我用DER格式生成RSA密鑰對和公開密鑰證書,並打開ssl(嘗試使用SecKeyGeneratePair生成,但難以導入公鑰到iOS,而SecKeyRawVerify仍然無法使用相同結果),並在我的數據上簽名Mac應用程序。然後,如果我在iOS上驗證此數據,驗證失敗並顯示-9809錯誤代碼,但是如果在mac驗證上執行相同的代碼,則成功。SecKeyRawVerify在mac上驗證但在iOS上失敗-9809

這裏是我的驗證碼:

NSString* certPath = [[NSBundle mainBundle] pathForResource: @"Public" ofType:@"der"]; 
NSData* certificateData = [NSData dataWithContentsOfFile: certPath]; 

SecCertificateRef certificateFromFile = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData); // load the certificate 

SecPolicyRef secPolicy = SecPolicyCreateBasicX509(); 

SecTrustRef trust; 
OSStatus statusTrust = SecTrustCreateWithCertificates(certificateFromFile, secPolicy, &trust); 
SecTrustResultType resultType; 
OSStatus statusTrustEval = SecTrustEvaluate(trust, &resultType); 
SecKeyRef publicKey = SecTrustCopyPublicKey(trust); 

NSString* licensingPolicyString = @"ZKL3YXtqtFcIeWRqSekNuCmtu/nvy3ApsbJ+8xad6cO/E8smLHGfDrTQ3h/38d0IMJcUThsVMyX8qtqILmPeTnBpZgJetBjb8kAfuPznzxOrIcYd27/50ThWv6guLqZL7j1apnfRZHAdMiozvEYH62sma1Q9qTl+W7qxEAxWs2AXDTQcF7nGciEM6MEohs8u879VNIE1VcPW8ahMoe25wf8pvBvrzE0z0MR4UFE3ZSWIeeQsiaUPYFwHbfQAOifaw/qIisjL5Su6WURoaSupWTMdQh3ZNyqZuYJaT70u8S7NgF3BzG8uBiYOUYsf6UayvkABmF0UuMdcvhPQefyhuXsiYWxsb3dFeGNoYW5nZSI6dHJ1ZSwiYWxsb3dTaGFmZXIiOnRydWUsInBvbGljeSBuYW1lIjp0cnVlfQ=="; 

size_t signedHashBytesSize = SecKeyGetBlockSize(publicKey); 

NSData* messageData = [[NSData alloc] initWithBase64EncodedData:[licensingPolicyString dataUsingEncoding: NSUTF8StringEncoding] options:0]; 

NSData* signatureData = [messageData subdataWithRange:NSMakeRange(0, signedHashBytesSize)]; 
NSData* rawMessageData = [messageData subdataWithRange: NSMakeRange(signedHashBytesSize, messageData.length - signedHashBytesSize)]; 


uint8_t sha1HashDigest[CC_SHA1_DIGEST_LENGTH]; 
CC_SHA1([rawMessageData bytes], (CC_LONG)[rawMessageData length], sha1HashDigest); 

OSStatus verficationResult = SecKeyRawVerify(publicKey, kSecPaddingPKCS1SHA1, sha1HashDigest, CC_SHA1_DIGEST_LENGTH, [signatureData bytes], [signatureData length]); 
CFRelease(publicKey); 
CFRelease(trust); 
CFRelease(secPolicy); 
CFRelease(certificateFromFile); 
if (verficationResult == errSecSuccess) NSLog(@"Verified"); 

是否有適用於Mac和iOS在數字簽名驗證一些區別?我沒有在蘋果的文檔中找到任何有關它的信息。

回答

0

經過對sign/verify的一些試驗後,我發現將填充協議改爲SecKeyRawVerify/SecKeyRawSign從kSecPaddingPKCS1SHA1改爲kSecPaddingPKCS1,解決了我的問題。不知道爲什麼它不能與kSecPaddingPKCS1SHA1配合使用,Apple的文檔中沒有提到過這些棄用。此外,我沒有在iOS上嘗試此代碼與8.3不同,所以也許是iOs8.3問題。

+2

即使更改填充,我也有同樣的問題。你是如何在OS X上籤署數據的?你是否使用變換明確地設置了填充? 'SecTransformSetAttribute(簽名者, kSecPaddingKey, kSecPaddingPKCS1Key, &錯誤);' – Maurizio

+0

我直接在'SecKeyRawSign(privateKeyRef, kSecPaddingPKCS1設置填充, (常量uint8_t *)[[自getHashBytes:明文]字節], CC_SHA1_DIGEST_LENGTH , (uint8_t *)signedHashBytes, &signedHashBytesSize );'和'SecKeyRawVerify'中的相同 –