我有一个私钥。以“ ---开始私钥...”开头的文本文件
我想使用该密钥来加密NSString。由于它是私钥,因此最好将其签名为NSString。
没有任何外部框架就能做到吗?
结果应该等同于php openssl_sign函数。
您无需外部资源或组件即可轻松解决此问题。
我发现了方法,并希望与他人分享,以便为他人提供帮助。
NSString * resourcePath = [[[NSBundle mainBundle] pathForResource:privateKeyResourceName ofType:@“ p12”]]; NSData * p12Data = [NSData dataWithContentsOfFile:resourcePath]; NSMutableDictionary *选项= [[NSMutableDictionary分配] init]; SecKeyRef privateKeyRef = NULL; //更改为您在此处使用的实际密码 [选项setObject:@“ _ YOURPASSWORDHERE__” forKey:(__ bridge id)kSecImportExportPassphrase]; CFArrayRef项目= CFArrayCreate(NULL,0,0,NULL); OSStatus securityError = SecPKCS12Import(((__ bridge CFDataRef)p12Data,(__bridge CFDictionaryRef)options,&items); 如果(securityError == noErr && CFArrayGetCount(items)> 0){ CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items,0); SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity); securityError = SecIdentityCopyPrivateKey(identityApp,&privateKeyRef); 如果(securityError!= noErr){ privateKeyRef = NULL; } } CFRelease(项目); privateKey = privateKeyRef; maxPlainLen = SecKeyGetBlockSize(privateKey)-12;
-(NSData *)toSha1AsData { // PHP使用ASCII编码,而不是UTF const char * s = [self cStringUsingEncoding:NSASCIIStringEncoding]; NSData * keyData = [NSData dataWithBytes:s length:strlen(s)]; //这是目标 uint8_t摘要[CC_SHA1_DIGEST_LENGTH] = {0}; //此函数对哈希数据 CC_SHA1(keyData.bytes,keyData.length,digest)进行无密钥SHA1哈希; //现在转换为NSData结构以使其再次可用 NSData * out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH] 返回; }
(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东西。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句