私は秘密鍵を持っています。「--- begin private key...」のように始まるテキスト ファイル
そのキーを使用して NSString を暗号化したい。これは秘密鍵であるため、NSString に署名した方がよいでしょう。
これは外部フレームワークなしで実行できますか?
結果は php の openssl_sign 関数と同等になるはずです。
私は秘密鍵を持っています。「--- begin private key...」のように始まるテキスト ファイル
そのキーを使用して NSString を暗号化したい。これは秘密鍵であるため、NSString に署名した方がよいでしょう。
これは外部フレームワークなしで実行できますか?
結果は php の openssl_sign 関数と同等になるはずです。
外部ソースやコンポーネントがなくても、これははるかに簡単に解決できます。
私はその方法を知り、それを共有したかったので、他の人を助けることができました.
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:privateKeyResourceName ofType:@"p12"];
NSData *p12Data = [NSData dataWithContentsOfFile:resourcePath];
NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
SecKeyRef privateKeyRef = NULL;
//ここで使用した実際のパスワードに変更します
[オプション 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(アイテム) > 0) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp =
(SecIdentityRef)CFDictionaryGetValue(identityDict、
kSecImportItemIdentity);
securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
if (securityError != noErr) {
privateKeyRef = NULL;
}
}
CFRelease(アイテム);
privateKey = privateKeyRef;
maxPlainLen = SecKeyGetBlockSize(privateKey) - 12;
- (NSData*)toSha1AsData {
// PHP は UTF ではなく ASCII エンコーディングを使用します
const char *s = [self cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
// これが目的地です
uint8_t ダイジェスト[CC_SHA1_DIGEST_LENGTH] = {0};
// この 1 つの関数は、ハッシュ データのキーなし SHA1 ハッシュを実行します
CC_SHA1(keyData.bytes、keyData.length、ダイジェスト);
// ここで NSData 構造に変換して、再び使用できるようにします
NSData *out = [NSData dataWithBytes:ダイジェスト長: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 をコンパイルする必要はありません。