验证 RSA 签名 iOS

2023-12-30

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

我在网上查了一下,这就是我想到的:

第一:使用我找到的信息生成私钥和自签名证书here https://github.com/superwills/iOSRSAPublicKeyEncryption.

// 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 https://stackoverflow.com/questions/10782826/digital-signature-for-a-file-using-openssl:

// 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.sig and license.txt到我的应用程序。

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

The 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 https://stackoverflow.com/questions/1595013/iphone-how-to-create-a-seckeyref-from-a-public-key-file-pem所以帖子。

对于签名验证我发现了以下函数

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 https://stackoverflow.com/questions/21724337/signing-and-verifying-on-ios-using-rsa

在我的项目中,我这样调用代码:

// 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我认为这就是问题所在。在里面苹果文档 https://developer.apple.com/library/ios/documentation/Security/Conceptual/CertKeyTrustProgGuide/03tasks/tasks.html我发现这可能是证书已过期的结果。尽管这里的情况似乎并非如此。但也许我生成证书的方式有问题?

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

I have uploaded http://up.indev.nl/RTR4y0Ou0L.zip具有生成的证书和此处引用的代码的 iOS 项目。也许这会派上用场。


问题出在你创建签名文件的方式上;按照相同的步骤,我能够生成等效的二进制文件signature.sig file.

通过查看内部hash在文件中我们可以看到 openssl 添加了一些前缀(并对哈希值进行了十六进制编码):

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

So 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: the malloc是泄漏


Edit:

为了让你现在的signature.sig文件按原样工作,您必须执行与 openssl 相同的步骤(添加前缀、十六进制哈希和换行符\n),然后将此数据传递给SecKeyRawVerify with 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

验证 RSA 签名 iOS 的相关文章

随机推荐

  • mysql DECLARE WHILE 外部存储过程如何?

    我对 mysql 相当陌生 但有 MS SQL 经验 是否有可能声明变量并使用while陈述 外部存储过程 我只找到了人们这样做的例子 1 procedure created 2 execute proc 3 drop proc 建议我正确
  • 我可以在 Android/IOS Webview 中使用 navigator.mediaDevices.getUserMedia 吗?

    我在 Android IOS 的本机应用程序中使用 web api 时遇到一些问题 在webview中 我渲染了一个html 我想使用相机拍照 我搜索web api并找到了一个方法 那就是 navigator mediaDevices ge
  • C++中加宽和缩小的区别?

    有什么区别widening and 缩小在 C 中 铸造是什么意思 铸造有哪些类型 这是一般的转换 而不是 C 特有的 加宽 转换是从一种类型到另一种类型的转换 其中 目标 类型具有比 源 更大的范围或精度 例如 int 到 long fl
  • 使用 BigQuery 进行日志分析

    我正在尝试使用 BigQuery 进行日志分析 具体来说 我有一个 appengine 应用程序和一个 javascript 客户端 它将向 BigQuery 发送日志数据 在 bigquery 中 我将完整的日志文本存储在一列中 同时还将
  • 自定义S3中的404页面

    我在亚马逊存储桶和实例方面几乎是个新手 我现在要做的是错误 404 的自定义错误页面 现在显示的是默认错误页面 显示非用户友好的 XML 告诉没有找到该文件 有什么好的方法可以做到这一点吗 我发现文档非常不清楚 它说 提供这个自定义错误文档
  • 如何在 DynamoDB 中过滤嵌套数组对象

    我对 AWS DynamoDB 非常初学者 我想使用 SENDTO emailAddress 扫描 DynamoDB 电子邮件受保护 cdn cgi l email protection 作为过滤器表达式 数据库结构如下所示 ID NAME
  • 具有自定义单元格的 UITableView 在 iOS 6 上绘制良好,但在 iOS 7 中完全白色

    我正在 Xcode 5 上构建一个针对 iOS 6 的应用程序 我在使用自定义单元格构建表格视图时遇到问题 有趣的是 它一直工作得很好 直到我今天更新到 Xcode 5 0 2 我不知道发生了什么变化 当我弄乱 iOS 7 SDK 附带的白
  • 如何使用 OpenXML Sdk 替换段落的文本

    我正在使用 Net OpenXml SDK 2 0 解析一些 Openxml word 文档 作为处理的一部分 我需要用其他句子替换某些句子 在迭代这些段落时 我知道何时找到需要替换的内容 但我对如何替换它感到困惑 例如 假设我需要替换句子
  • 全局键盘挂钩不起作用

    我创建了一个全局键盘挂钩 Hook 在 DLL 中创建 pragma comment linker SECTION SHARED RWS pragma data seg SHARED static HHOOK hkb NULL static
  • 为什么 Flask 限速解决方案使用 Redis?

    我想限制我的 Flask API 的速率 我找到了2个解决方案 The 烧瓶限制器 https flask limiter readthedocs io en stable 扩大 使用 Redis 的 Flask 网站的片段 http fl
  • 为什么相等的整数与相等的列表的行为不同?

    这个问题更多的是出于好奇 我一直在阅读Python中int对象的实现细节 1 http www laurentluce com posts python integer objects implementation and 2 http s
  • 仅 X 上的 Android 位图平铺

    我想使用仅在水平方向上平铺的位图 有什么方法可以做到这一点 以便它仅在 X 上扩展 就像 CSS 上的重复 x 一样 我使用以下代码 但位图平铺水平和垂直
  • 从 byte[] 返回 FileResult

    我正在开发 ASP NET Core API API 是数据库驱动的 我将图像存储在数据库中 我的ArtistImage cs实体看起来像这样 艺术家图像 cs public class ArtistImage public int Id
  • 在绘图标题中使用多种字体大小 (Python)

    我有一个图表标题 它使用换行符跨越多行 我希望第一行之后的所有内容都采用较小的字体 实际上是副标题 但无法找到实现此目的的方法 在这里看不到任何类似的问题 import plotly graph objs as go data layout
  • Gatsby 在使用带有 '@use 'sass:color' 的 Sass 文件后失败

    我正在建立一个盖茨比项目gatsby plugin sass my gatsby config js file module exports plugins gatsby plugin resolve src gatsby plugin s
  • 是否可以使 bash shell 脚本与另一个命令行程序交互?

    我在运行 bash shell 的 Linux 终端中使用交互式命令行程序 我有一个明确的命令序列输入到 shell 程序中 程序将其输出写入标准输出 其中一个命令是 保存 命令 它将前一个运行的命令的输出写入磁盘的文件中 一个典型的循环是
  • if else 在列表理解中[重复]

    这个问题在这里已经有答案了 我有一个清单l l 22 13 45 50 98 69 43 44 1 对于45以上的数字 我想加1 对于小于它的数字 5 I tried x 1 for x in l if x gt 45 else x 5 但
  • Jupyter 的 Octave 内核无法在 Windows 10 上运行

    我尝试使用 pip 为 jupyter 安装八度内核 如此处建议的https github com calysto octave kernel https github com calysto octave kernel 但我在创建新笔记本
  • 根据 Firebase 中的子项过滤产品

    我试图弄清楚如何根据 Firebase 中的子子节点来过滤产品 我的设置如下 products product1 author 12345 title Awesome description more awesome product2 au
  • 验证 RSA 签名 iOS

    在我的静态库中 我有一个许可证文件 我想确保它是由我自己生成的 并且没有被更改 所以我的想法是使用我读过的 RSA 签名 我在网上查了一下 这就是我想到的 第一 使用我找到的信息生成私钥和自签名证书here https github com