验证 RSA 签名 iOS

Verifying RSA Signature iOS

在我的静态库中,我有一个许可证文件。我想确保它是由我自己生成的(并且没有被更改)。所以我的想法是使用我读过的 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 来验证签名。

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

- (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 post.

对于签名验证,我找到了以下函数

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!");
}

目前它总是说:"Something went wrong!" 虽然我不确定是什么。我发现获取 public 密钥的方法中的信任结果等于 kSecTrustResultRecoverableTrustFailure 我认为这是问题所在。在 Apple documentation 中,我发现这可能是证书过期的结果。尽管这里似乎并非如此。但也许我生成证书的方式有问题?

我的问题归结为,我做错了什么,我该如何解决?我发现这方面的文档非常稀疏且难以阅读。

我有一个 uploaded 一个 iOS 项目,其中包含生成的证书和此处引用的代码。也许这会派上用场。

问题出在您创建签名文件的方式上;按照相同的步骤,我能够生成等效的二进制 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),然后传递此数据到 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;
}