验证RSA签名iOS

时间:2015-10-16 14:28:14

标签: ios objective-c cocoa openssl digital-signature

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

我看过互联网,这就是我想出来的:

首先:使用我找到的信息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.cersignature.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 个答案:

答案 0 :(得分: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

散列&签名步骤正确,示例输出: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文件按原样运行,您必须生成与openssl相同的步骤(添加前缀,十六进制哈希和换行符\n),然后将此数据传递给SecKeyRawVerify kSecPaddingPKCS1而非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;
}
相关问题