使用RSA在iOS上签名和验证 [英] Signing and Verifying on iOS using RSA
问题描述
如何使用RSA密钥在iOS上签名和验证某些数据(最好使用系统自己的 libcommonCrypto
)?
How to sign and verify some data on iOS with an RSA key (preferably using the system own libcommonCrypto
)?
推荐答案
由于在StackOverflow和Apple文档上几乎没有关于签名和验证的任何知识,我不得不在iOS头文件中手动浏览并找到 SecKeyRawSign
和 SecKeyRawVerify
。以下代码行似乎有效。
Since there hasn't been nearly any knowledge about signing and verifying found on StackOverflow and the Apple docs, I had to manually browse around in the iOS header files and found SecKeyRawSign
and SecKeyRawVerify
. The following lines of code seem to work.
签署NSData(使用带有RSA的SHA256):
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;
}
验证(使用带有RSA的SHA256):
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包装程序库,它使加密工作变得非常容易。请参阅下面的示例。
There is a very good alternative available which utilizes OpenSSL directly instead of libCommonCrypto. MIHCrypto is a well-designed Objective-C wrapper library for OpenSSL which makes working with cryptography very easy. See the example below.
生成密钥很简单:
MIHAESKeyFactory *factory = [[MIHAESKeyFactory alloc] init];
id<MIHSymmetricKey> aesKey = [factory generateKey];
或者从文件加载密钥:
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 页面。
For more examples browse the MIHCrypto page.
这篇关于使用RSA在iOS上签名和验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!