我有一把私钥。文本文件以“---开始私钥......”开头。
我想使用该密钥加密NSString。因为它的私钥,最好叫它签署一个NSString。
这可以在没有任何外部框架的情况下完成吗?
结果应该等同于php openssl_sign函数。
答案 0 :(得分:4)
您需要使用的iOS SDK框架称为 CommonCrypto
。这是一个非常好的article,它描述了正确的方法。
编辑:我错过了关于与PHP函数openssl_sign
的兼容性的部分。下面的解决方案解决了这个问题。
这样做以便与PHP函数openssl_sign
兼容的方法是使用OpenSSL库。 openssl_sign
函数在内部使用OpenSSL的EVP API来使用私钥加密输入字符串,并计算该加密字符串的SHA-1哈希摘要。然后将此哈希摘要转换为Base64编码的字符串是常见的。
不幸的是,iOS SDK不包含OpenSSL,但很容易构建它。以下有关构建OpenSSL for iOS的说明来自this blog post,并在此处转载以提供问题的完整解决方案。
在终端中,按照以下步骤构建iOS的OpenSSL库:
# Make a directory in which to run the build
mkdir ~/openssl-ios
cd ~/openssl-ios
# Download the openssl source (verify the file before using it in production!)
curl -O http://www.openssl.org/source/openssl-1.0.1e.tar.gz
# Download the openssl iOS build script
curl -O https://raw.github.com/Raphaelios/raphaelios-scripts/master/openssl/build-openssl.sh
# Make the build script executable
chmod +x build-openssl.sh
# Run the script (takes about 3min on an Intel Core i5)
./build-openssl.sh
这将需要几分钟但是一旦完成,您可以验证构建库是一个通用库,您可以使用以下命令在iOS设备和iOS模拟器中使用它:
lipo -info ~/openssl-ios/lib/*.a
现在已经构建了OpenSSL库,让我们继续编写代码以签署字符串。
首先,我们需要设置Xcode项目以链接OpenSSL库。拖拽将libcrypto.a
和libssl.a
同时放入iOS项目的 Project Navigator 中的 Frameworks 组。在项目的构建设置中,将以下内容添加到标题搜索路径设置中:
~/openssl-ios/include/include
接下来,在Objective-C Category
类上创建一个名为openssl_sign
的新NSString
文件。在NSString+openssl_sign.h
中,定义以下界面:
@interface NSString (openssl_sign)
- (NSString *)signStringWithPrivateKey:(NSData *)privateKey;
@end
在NSString+openssl_sign.m
中,添加以下标头导入:
#import <openssl/evp.h>
#import <openssl/pem.h>
并添加signStringWithPrivateKey:
的以下实现:
@implementation NSString (openssl_sign)
- (NSString *)signStringWithPrivateKey:(NSData *)privateKeyData
{
BIO *publicBIO = NULL;
EVP_PKEY *privateKey = NULL;
if ((publicBIO = BIO_new_mem_buf((unsigned char *)[privateKeyData bytes], [privateKeyData length])) == NO) {
NSLog(@"BIO_new_mem_buf() failed!");
return nil;
}
if (PEM_read_bio_PrivateKey(publicBIO, &privateKey, NULL, NULL) == NO) {
NSLog(@"PEM_read_bio_PrivateKey() failed!");
return nil;
}
const char * cString = [self cStringUsingEncoding:NSUTF8StringEncoding];
unsigned int stringLength = [self length];
unsigned char * signatureBuffer[EVP_MAX_MD_SIZE];
int signatureLength;
EVP_MD_CTX msgDigestContext;
const EVP_MD * msgDigest = EVP_sha1();
EVP_MD_CTX_init(&msgDigestContext);
EVP_SignInit(&msgDigestContext, msgDigest);
EVP_SignUpdate(&msgDigestContext, cString, stringLength);
if (EVP_SignFinal(&msgDigestContext, (unsigned char *)signatureBuffer, (unsigned int *)&signatureLength, privateKey) == NO) {
NSLog(@"Failed to sign string.");
return nil;
}
EVP_MD_CTX_cleanup(&msgDigestContext);
EVP_PKEY_free(privateKey);
NSData *signatureData = [NSData dataWithBytes:signatureBuffer length:signatureLength];
NSString *signature = [signatureData base64EncodedStringWithOptions:0];
return signature;
}
@end
在将要对字符串进行签名的类中,您现在可以导入NSString+openssl_sign.h
并对字符串进行签名,如下所示:
NSData *privateKey = ...; // Read the .pem file into a NSData variable
NSString *helloSignature = [@"hello" signStringWithPrivateKey:privateKey];
您可以使用终端中的以下命令验证签名是否相同:
echo -n "hello" | openssl dgst -sha1 -sign priv.pem | openssl enc -base64 | tr -d '\n'
答案 1 :(得分:1)
没有外部资源或组件,您可以更轻松地解决这个问题。
我发现了如何并希望分享它,以便我可以帮助别人。
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:privateKeyResourceName ofType:@"p12"]; NSData *p12Data = [NSData dataWithContentsOfFile:resourcePath]; NSMutableDictionary * options = [[NSMutableDictionary alloc] init]; SecKeyRef privateKeyRef = NULL; //change to the actual password you used here [options setObject:@"_YOURPASSWORDHERE__" forKey:(__bridge id)kSecImportExportPassphrase]; CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data, (__bridge CFDictionaryRef)options, &items); if (securityError == noErr && CFArrayGetCount(items) > 0) { CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0); SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity); securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef); if (securityError != noErr) { privateKeyRef = NULL; } } CFRelease(items); privateKey = privateKeyRef; maxPlainLen = SecKeyGetBlockSize(privateKey) - 12;
- (NSData*)toSha1AsData { // PHP uses ASCII encoding, not UTF const char *s = [self cStringUsingEncoding:NSASCIIStringEncoding]; NSData *keyData = [NSData dataWithBytes:s length:strlen(s)]; // This is the destination uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0}; // This one function does an unkeyed SHA1 hash of your hash data CC_SHA1(keyData.bytes, keyData.length, digest); // Now convert to NSData structure to make it usable again NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH] return out; }
(NSData *)signSha1Data:(NSData *)data {
size_t plainLen = [data length];
if (plainLen > maxPlainLen)
{
NSLog(@"content(%ld) is too long, must < %ld", plainLen, maxPlainLen);
return nil;
}
void *plain = malloc(plainLen);
[data getBytes:plain
length:plainLen];
size_t cipherLen = 128; // currently RSA key length is set to 128 bytes
void *cipher = malloc(cipherLen);
OSStatus returnCode = SecKeyRawSign(privateKey, kSecPaddingPKCS1SHA1,
plain, plainLen, cipher, &cipherLen);
NSData *result = nil;
if (returnCode != 0) {
NSLog(@"SecKeyEncrypt fail. Error Code: %ld", returnCode);
}
else {
result = [NSData dataWithBytes:cipher
length:cipherLen];
}
free(plain);
free(cipher);
return result;
}
它工作得很好,没有任何外部库。没有必要编译一些奇怪的openssl东西。