Forum Xamarin.iOS

Create Key in iOS keychain

PerdruPerdru Member ✭✭

I'm trying to use 'SecKey.CreateRandomKey()' to create a secure EC keypair, ultimately with the goal of storing the private key in the secure enclave. Using Xamarin.iOS I keep getting a "-50 Key Generation failed", but it works as expected with native Objective-C:


using (var access = new SecAccessControl(SecAccessible.WhenUnlockedThisDeviceOnly, SecAccessControlCreateFlags.PrivateKeyUsage)) {
    var keyParameters = new SecKeyGenerationParameters
        KeyType = SecKeyType.ECSecPrimeRandom,
        KeySizeInBits = 256,
        Label = keyTag,
        PrivateKeyAttrs = new SecKeyParameters
            IsPermanent = true,
            ApplicationTag = keyTagData,
            AccessControl = access,

    NSError error;                  
    var key = SecKey.CreateRandomKey(keyParameters, out error);
    if (key == null)
        throw new NSErrorException(error);
    return key;


CFErrorRef error;
SecAccessControlRef access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage, &error);
NSDictionary* keyParameters =
  @{ (id)kSecAttrKeyType:               (id)kSecAttrKeyTypeECSECPrimeRandom,
     (id)kSecAttrKeySizeInBits:         @256,
     (id)kSecAttrLabel:                 label,
       @{ (id)kSecAttrIsPermanent:    @YES,
          (id)kSecAttrApplicationTag: tag,
          (id)kSecAttrAccessControl:  (__bridge id)access,

SecKeyRef key = SecKeyCreateRandomKey((__bridge CFDictionaryRef)keyParameters, &error);


  • PerdruPerdru Member ✭✭

    After playing around with it some more, I found this SO post: which suggested that IsPermanent = true was to blame. Removing that line lets the key generation succeed, but then I can't access the key through SecKeyChain.QueryAs...(). According to that post, It should only error -50 in Xcode unit tests on iOS Simulator, so IDK what's going on here. Maybe this problem will disappear if I run on a physical device instead of the Simulator? Has anyone else gotten this to work?

  • PerdruPerdru Member ✭✭

    Ok, after finally getting a physical device to test on, I found that both versions do work equivalently. It's a shame that the simulator doesn't simulate this aspect of iDevices, and that it behaves differently when using XCode vs using VS.

  • PerdruPerdru Member ✭✭

    I feel stupid. This was a really simple fix, it just took a while to find it. I followed the example in specifically adding the default Entitlements.plist to the iOS Bundle Signing settings in VS and everything works now.

Sign In or Register to comment.