0
我試圖在iOS上使用橢圓曲線算法簽名數據並驗證簽名。創建密鑰工作得很好,但試圖簽署數據返回錯誤-1
- 這是非常通用的。在iOS上使用kSecAttrKeyTypeEC鍵簽名數據
的鍵創建如下:
publicKeyRef = NULL;
privateKeyRef = NULL;
NSDictionary * privateKeyAttr = @{(id)kSecAttrIsPermanent : @1,
(id)kSecAttrApplicationTag : privateTag};
NSDictionary * publicKeyAttr = @{(id)kSecAttrIsPermanent : @1,
(id)kSecAttrApplicationTag : privateTag};
NSDictionary * keyPairAttr = @{(id)kSecAttrKeySizeInBits : @(keySize),
(id)kSecAttrKeyType : (id)kSecAttrKeyTypeEC,
(id)kSecPrivateKeyAttrs : privateKeyAttr,
(id)kSecPublicKeyAttrs : publicKeyAttr};
OSStatus status = SecKeyGeneratePair((CFDictionaryRef)keyPairAttr, &publicKeyRef, &privateKeyRef);
這將返回狀態0
,到目前爲止,一切順利。實際簽約情況是這樣的:
- (NSData *) signData:(NSData *)dataToSign withPrivateKey:(SecKeyRef)privateKey {
NSData * digestToSign = [self sha1DigestForData:dataToSign];
size_t signedHashBytesSize = SecKeyGetBlockSize(privateKey);
uint8_t * signedHashBytes = malloc(signedHashBytesSize * sizeof(uint8_t));
memset((void *)signedHashBytes, 0x0, signedHashBytesSize);
OSStatus signErr = SecKeyRawSign(privateKey,
kSecPaddingPKCS1,
digestToSign.bytes,
digestToSign.length,
(uint8_t *)signedHashBytes,
&signedHashBytesSize);
NSLog(@"Status: %d", signErr);
NSData * signedHash = [NSData dataWithBytes:(const void *)signedHashBytes length:(NSUInteger)signedHashBytesSize];
if (signedHashBytes) free(signedHashBytes);
return (signErr == noErr) ? signedHash : nil;
}
- (NSData *)sha1DigestForData:(NSData *)data {
NSMutableData *result = [[NSMutableData alloc] initWithLength:CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, (CC_LONG) data.length, result.mutableBytes);
return result;
}
的調用SecKeyRawSign()
回報-1
。
這是從https://forums.developer.apple.com/message/95740#95740
什麼是用於簽名數據的EC鍵選擇正確的方式適應?這裏有一個RSA密鑰的工作解決方案:Signing and Verifying on iOS using RSA但我無法將它適配到EC密鑰。