I'm trying to sign data and verify the signature using Elliptic Curve algorithm on iOS. Creating the keys works well enough, but attempting to sign the data returns error -1 - which is very generic.
The keys are created as follows:
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);
This returns status 0, so far so good. The actual signing happens like this:
- (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;
}
The call to SecKeyRawSign() returns -1.
This is adapted from https://forums.developer.apple.com/message/95740#95740
What is the correct way to use an EC key for signing data? There is a working solution for RSA keys here: Signing and Verifying on iOS using RSA but I was unable to adapt it to EC keys.