Search code examples
iosobjective-csigningkey-pairnativescript-plugin

Generate EC keypair for iOS in NativeScript plugin


Preamble: I am trying to create an elliptic curve key pair in my NativeScript plugin (thus I am forced to use Objective-C) for signing and verification purpose.

At first I want to say that the presented state below is the result of a lot of tries doing it in different ways (I am sitting on this for days, unfortunately) and I considered not only this approach. At the beginning of this project I simply followed the Apple docs and thought I will succeed easily. What a misbelief.

My requirements: to keep it easy I want to store the private key inside of the Keychain (Secure Enclave would be the next step), and calculate the public key via SecKeyCopyPublicKey after I retrieved the key via SecItemCopyMatching, like described in the Apple docs.

Status quo: the model for this originally came from the here. I never got it working with SecKeyCreateRandomKey thus I am trying to use SecKeyGeneratePair atm. What I currently implemented looks like this:

const privAttr: NSMutableDictionary<string, any> = NSMutableDictionary.new<string, any>();
privAttr.setObjectForKey("my.tag.sign.private", kSecAttrApplicationTag);
privAttr.setObjectForKey(kCFBooleanTrue, kSecAttrIsPermanent);

const pubAttr: NSMutableDictionary<string, any> = NSMutableDictionary.new<string, any>();
pubAttr.setObjectForKey("my.tag.sign.public", kSecAttrApplicationTag);
pubAttr.setObjectForKey(kCFBooleanTrue, kSecAttrIsPermanent);

const param: NSMutableDictionary<string, any> = NSMutableDictionary.new<string, any>();
param.setObjectForKey(kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyType);
param.setObjectForKey(256, kSecAttrKeySizeInBits);
param.setObjectForKey(privAttr, kSecPrivateKeyAttrs);
param.setObjectForKey(pubAttr, kSecPublicKeyAttrs);

let pubKeyRef = new interop.Reference<any>();
let privKeyRef = new interop.Reference<any>();
const status = SecKeyGeneratePair(param, pubKeyRef, privKeyRef);

Currently I am getting an error -50. According to OSStatus.com this means that my given parameters are not valid at some point. I do not know what exactly is the problem.

My question: how can I generate a keypair where at least the private key is implicitely stored in the keychain and I successfully can retrieve the public key via SecKeyCopyPublicKey afterwards.

Thanks for any valuable hint and your help.

Cordially, David


Solution

  • After trying out several settings I found a solution for this. My answer is documented in the following GitHub issue.

    Best regards, David