2015-10-16 55 views
11

在我的静态库中,我有一个许可证文件。我想确定的是我自己生成的(并且没有被改变)。所以这个想法是使用我读过的RSA签名。验证RSA签名iOS

我看着在互联网上,这是我想出了:

首先:生成私钥和自签名证书与我发现here的信息。

// Generate private key 
openssl genrsa -out private_key.pem 2048 -sha256 

// Generate certificate request 
openssl req -new -key private_key.pem -out certificate_request.pem -sha256 

// Generate public certificate 
openssl x509 -req -days 2000 -in certificate_request.pem -signkey private_key.pem -out certificate.pem -sha256 

// Convert it to cer format so iOS kan work with it 
openssl x509 -outform der -in certificate.pem -out certificate.cer -sha256 

在那之后,我创建了一个许可文件(带有日期和应用标识符内容)和等,使得文件基于信息产生的签名发现here

// Store the sha256 of the licence in a file 
openssl dgst -sha256 licence.txt > hash 

// And generate a signature file for that hash with the private key generated earlier 
openssl rsautl -sign -inkey private_key.pem -keyform PEM -in hash > signature.sig 

其中我认为一切正常。我没有得到任何错误,并按预期得到密钥和证书以及其他文件。

接下来我将certificate.cer,signature.siglicense.txt复制到我的应用程序中。

现在我想检查签名是否由我签名,并且对于license.txt有效。我发现它非常难找到任何很好的例子,但是这是我目前:

Seucyrity.Framework我发现使用SecKeyRef引用RSA密钥/证书和SecKeyRawVerify来验证签名。

我有以下方法从文件加载公钥。

- (SecKeyRef)publicKeyFromFile:(NSString *) path 
{ 
    NSData *myCertData = [[NSFileManager defaultManager] contentsAtPath:path]; 
    CFDataRef myCertDataRef = (__bridge CFDataRef) myCertData; 

    SecCertificateRef cert = SecCertificateCreateWithData (kCFAllocatorDefault, myCertDataRef); 
    CFArrayRef certs = CFArrayCreate(kCFAllocatorDefault, (const void **) &cert, 1, NULL); 
    SecPolicyRef policy = SecPolicyCreateBasicX509(); 
    SecTrustRef trust; 
    SecTrustCreateWithCertificates(certs, policy, &trust); 
    SecTrustResultType trustResult; 
    SecTrustEvaluate(trust, &trustResult); 
    SecKeyRef pub_key_leaf = SecTrustCopyPublicKey(trust); 

    if (trustResult == kSecTrustResultRecoverableTrustFailure) 
    { 
     NSLog(@"I think this is the problem"); 
    } 
    return pub_key_leaf; 
} 

这是根据this SO帖子。

对于签名验证,我发现下面的函数

BOOL PKCSVerifyBytesSHA256withRSA(NSData* plainData, NSData* signature, SecKeyRef publicKey) 
{ 
    size_t signedHashBytesSize = SecKeyGetBlockSize(publicKey); 
    const void* signedHashBytes = [signature bytes]; 

    size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH; 
    uint8_t* hashBytes = malloc(hashBytesSize); 
    if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], hashBytes)) { 
     return nil; 
    } 

    OSStatus status = SecKeyRawVerify(publicKey, 
             kSecPaddingPKCS1SHA256, 
             hashBytes, 
             hashBytesSize, 
             signedHashBytes, 
             signedHashBytesSize); 

    return status == errSecSuccess; 
} 

这是从here

采取在项目中,我调用的代码如下所示:

// Get the licence data 
NSString *licencePath = [[NSBundle mainBundle] pathForResource:@"licence" ofType:@"txt"]; 
NSData *data = [[NSFileManager defaultManager] contentsAtPath:licencePath]; 

// Get the signature data 
NSString *signaturePath = [[NSBundle mainBundle] pathForResource:@"signature" ofType:@"sig"]; 
NSData *signature = [[NSFileManager defaultManager] contentsAtPath:signaturePath]; 

// Get the public key 
NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"cer"]; 
SecKeyRef publicKey = [self publicKeyFromFile:publicKeyPath]; 

// Check if the signature is valid with this public key for this data 
BOOL result = PKCSVerifyBytesSHA256withRSA(data, signature, publicKey); 

if (result) 
{ 
    NSLog(@"Alright All good!"); 
} 
else 
{ 
    NSLog(@"Something went wrong!"); 
} 

目前,它总是说: “出了些问题!”尽管我不确定是什么。我发现信任导致取得公钥的方法等于kSecTrustResultRecoverableTrustFailure,我认为这是问题所在。在Apple documentation我发现这可能是已过期的证书的结果。虽然这似乎并不是这种情况。但是,我生成证书的方式可能有问题吗?

我的问题归结为,我做错了什么,我怎么能解决这个问题?我发现这个文档很稀少,很难阅读。

我有uploaded一个iOS项目与生成的证书和在这里引用的代码。也许这可能派上用场。

+1

如果你看一下清单3- 5在你指出的文档中,你会看到它列出了“AllStatusBits”。当你遇到那个错误时,你能弄清楚什么是状态位? –

+0

嗨,当我尝试合并该代码时,第一个错误之一是'AllStatusBits'类型'CSSM_TP_APPLE_CERT_STATUS'是未知的,我似乎无法找到一个工作头文件来包含获取该类型。在互联网上,我发现它可能是'#import ',但这个在iOS上不存在(不再是?)。 - 我已经[上传](http://up.indev.nl/RTR4y0Ou0L.zip)我的项目与代码和证书,也许有帮助。 – Matthijn

+0

是的,我只是双重检查,但我[已经](http://up.indev.nl/C5OHOFziPO.png)添加安全框架。也许这已经在iOS版本的其他地方移动了? – Matthijn

回答

8

问题在于您创建签名文件的方式;遵循相同的步骤,我能够生成二进制等效文件signature.sig

通过查找hash文件中,我们可以看到的OpenSSL增加一些前缀(和十六进制编码哈希):

$ cat hash 
SHA256(licence.txt)= 652b23d424dd7106b66f14c49bac5013c74724c055bc2711521a1ddf23441724 

所以signature.sig是基于而不是license.txt

通过使用您的样本和创建签名文件:

openssl dgst -sha256 -sign certificates/private_key.pem licence.txt > signature.sig 

散列&签署STE p得到正确的,样本输出:Alright All good!


我的文件的最终状态,以防万一

- (SecKeyRef)publicKeyFromFile:(NSString *) path 
{ 
    NSData * certificateData = [[NSFileManager defaultManager] contentsAtPath:path]; 
    SecCertificateRef certificateFromFile = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData); 
    SecPolicyRef secPolicy = SecPolicyCreateBasicX509(); 
    SecTrustRef trust; 
    SecTrustCreateWithCertificates(certificateFromFile, secPolicy, &trust); 
    SecTrustResultType resultType; 
    SecTrustEvaluate(trust, &resultType); 
    SecKeyRef publicKey = SecTrustCopyPublicKey(trust); 
    return publicKey; 
} 

BOOL PKCSVerifyBytesSHA256withRSA(NSData* plainData, NSData* signature, SecKeyRef publicKey) 
{ 
    uint8_t digest[CC_SHA256_DIGEST_LENGTH]; 
    if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], digest)) 
     return NO; 

    OSStatus status = SecKeyRawVerify(publicKey, 
             kSecPaddingPKCS1SHA256, 
             digest, 
             CC_SHA256_DIGEST_LENGTH, 
             [signature bytes], 
             [signature length]); 

    return status == errSecSuccess; 
} 

PS:在malloc是泄漏


编辑:

为了使您当前的signature.sig文件能够像我一样工作S,你必须产生相同的步骤中OpenSSL的(加前缀,十六进制哈希值和一个换行符\n),那么这个数据传递给SecKeyRawVerifykSecPaddingPKCS1而不是kSecPaddingPKCS1SHA256

BOOL PKCSVerifyBytesSHA256withRSA(NSData* plainData, NSData* signature, SecKeyRef publicKey) 
{ 
    uint8_t digest[CC_SHA256_DIGEST_LENGTH]; 
    if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], digest)) 
     return NO; 

    NSMutableString *hashFile = [NSMutableString stringWithFormat:@"SHA256(licence.txt)= "]; 
    for (NSUInteger index = 0; index < sizeof(digest); ++index) 
     [hashFile appendFormat:@"%02x", digest[index]]; 

    [hashFile appendString:@"\n"]; 
    NSData *hashFileData = [hashFile dataUsingEncoding:NSNonLossyASCIIStringEncoding]; 

    OSStatus status = SecKeyRawVerify(publicKey, 
             kSecPaddingPKCS1, 
             [hashFileData bytes], 
             [hashFileData length], 
             [signature bytes], 
             [signature length]); 

    return status == errSecSuccess; 
} 
+0

你仍然在'SecTrustEvaluate'中获得'kSecTrustResultRecoverableTrustFailure',但是它正在成功验证签名 – Lefteris

+0

我认为kSecTrustResultRecoverableTrustFailure问题是您的证书是自签名的,如果您希望它正确成功所有信任链必须有效;您必须从(苹果)可信任的权威机构获得证书。 (ver * s * gn之类的) – blld

+0

或者在主机iOS设备上安装你的证书(这似乎不是一种选择) – blld