gpt4 book ai didi

ios - 使用 RSA 在 iOS 上签名和验证

转载 作者:IT王子 更新时间:2023-10-29 08:08:49 26 4
gpt4 key购买 nike

如何在 iOS 上使用 RSA key 对一些数据进行签名和验证(最好使用系统自带的 libcommonCrypto)?

最佳答案

由于在 StackOverflow 和 Apple 文档上几乎没有关于签名和验证的任何知识,我不得不手动浏览 iOS 头文件并找到 SecKeyRawSignSecKeyRawVerify 。以下代码行似乎有效。


签署 NSData(使用 SHA256 和 RSA):

NSData* PKCSSignBytesSHA256withRSA(NSData* plainData, SecKeyRef privateKey)
{
size_t signedHashBytesSize = SecKeyGetBlockSize(privateKey);
uint8_t* signedHashBytes = malloc(signedHashBytesSize);
memset(signedHashBytes, 0x0, signedHashBytesSize);

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

SecKeyRawSign(privateKey,
kSecPaddingPKCS1SHA256,
hashBytes,
hashBytesSize,
signedHashBytes,
&signedHashBytesSize);

NSData* signedHash = [NSData dataWithBytes:signedHashBytes
length:(NSUInteger)signedHashBytesSize];

if (hashBytes)
free(hashBytes);
if (signedHashBytes)
free(signedHashBytes);

return signedHash;
}

验证(使用 SHA256 和 RSA):

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;
}

备选方案 (OpenSSL):

有一个非常好的替代方案可用,它直接使用 OpenSSL 而不是 libCommonCrypto。 MIHCrypto是为 OpenSSL 精心设计的 Objective-C 包装器库,它使密码学工作变得非常容易。请参见下面的示例。

生成 key 就是这么简单:

MIHAESKeyFactory *factory = [[MIHAESKeyFactory alloc] init];
id<MIHSymmetricKey> aesKey = [factory generateKey];

或者从文件中加载 key :

NSData *privateKeyData = [[NSFileManager defaultManager] contentsAtPath:"mykey.pem"];
MIHRSAPrivateKey *privateKey = [[MIHRSAPrivateKey alloc] initWithData:privateKeyData];

现在签署一些东西:

NSError *signingError = nil;
NSData *message = // load something to sign from somewhere
NSData *signature = [privateKey signWithSHA256:message error:&signingError]

有关更多示例,请浏览 MIHCrypto页面。

关于ios - 使用 RSA 在 iOS 上签名和验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21724337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com