0

I'm developing a Xamarin Forms app, and in iOS I want to create a RSA key-pair and be able to store the key-pair in the iOS KeyChain and retrieve the publicKey from iOS KeyChain anytime i want to. However i'm facing some problems due to the lack of documentation available on the internet about this issue. So i created my RSA key pair this way, since i have to send the public key in DER format to a server (using BouncyCastle). `

        RsaKeyPairGenerator generator = new RsaKeyPairGenerator();

        generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

        AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();

        RsaKeyParameters keyParam = (RsaKeyParameters)keyPair.Public;

        var info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyParam);

        byte[] RsaBytes = info.GetEncoded();

`

and then i need to store the keys on KeyChain but i can't find anything that helps me so i tried this way (byte[] value = RsaBytes):

`        private void StoreKeysInKeychain(string key, byte[] value)
        {
        SecRecord record = new SecRecord(SecKind.GenericPassword)
                    {
                        ValueData = NSData.FromArray(value),
                        Generic = NSData.FromString(key)
                    };
        record.AccessControl = new SecAccessControl(SecAccessible.WhenUnlocked, SecAccessControlCreateFlags.TouchIDAny);
        SecStatusCode  err = SecKeyChain.Add(record);
    }`

First, i don't know if this is the best way to store anything is iOS KeyChain. Second, when i get the 'ValueData' from KeyChain, i can't convert it back to a byte[] so i can't get my publicKey again anymore. I get the key using the following method

         NSData GetRecordsFromKeychain(string key)
                {
                    SecStatusCode res;
                    var rec = new SecRecord(SecKind.GenericPassword)
                    {
                        Generic = NSData.FromString(key)
                    };

                    SecRecord match = SecKeyChain.QueryAsRecord(rec, out res);
                    if (match != null)
                    {
                        // nsdata object :  match.ValueData;
                        return match.ValueData;
                    }
                    return null;
                }

and i try to convert it back to a byte[] that represents my public key using the following methods:

    byte[] marshalBytes = new byte[nsdata.Length];
    System.Runtime.InteropServices.Marshal.Copy(nsdata.Bytes, marshalBytes, 0, Convert.ToInt32(nsdata.Length));
    byte[] storedBytes = ToByte(nsdata);
    byte[] convertedBytes = nsdata.ToArray();

No one of them is the same as RsaBytes:

    bool result1 = RsaBytes.SequenceEqual(storedBytes);         // FALSE
    bool result2 = RsaBytes.SequenceEqual(convertedBytes);  // FALSE
    bool result3 = storedBytes.SequenceEqual(convertedBytes); // TRUE
    bool result4 = marshalBytes.SequenceEqual(RsaBytes);    // FALSE
    bool result5 = marshalBytes.SequenceEqual(storedBytes);     // TRUE

So, summing up all the problems

1 - I don't know the best way to create an RSA key pair in iOS and get publicKey DER-encoded (so I used BouncyCastle)

2 - Don't know how to store it properly on KeyChain

3 - I can access the information i stored, however it's useless since I can't convert it back to a publicKey

4 - When trying to access the information the user should be prompt to use TouchID, always.

I can't find samples of this in the internet... I would really appreciate some help. Many thanks to everyone.

1 Answer 1

1

I am still struggeling with getting SecAccessControl to work the way i want it too, so i can only help you with 1-3.

In my iOS apps i store a key pair using the SecKey.CreateRandomKey function. To use this function you have to create an NSDictionary that holds the attributes used for the key generation.

private NSDictionary BuildKeyPairAttributes(int keySize)
    {
        IList<object> keyBuilder = new List<object>();
        IList<object> valueBuilder = new List<object>();

        keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrIsPermanent);
        keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrApplicationTag);
        keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrAccessible);

        valueBuilder.Add(NSNumber.FromBoolean(true));
        valueBuilder.Add(KeyAlias);
        valueBuilder.Add(IOSConstants.Preloaded.constKSecAccessibleWhenPasscodeSetThisDeviceOnly);

        NSDictionary privateKeyAttr = NSDictionary.FromObjectsAndKeys(valueBuilder.ToArray(), keyBuilder.ToArray());

        keyBuilder.Clear();
        valueBuilder.Clear();

        keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrKeyType);
        keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrKeySize);
        keyBuilder.Add(IOSConstants.Preloaded.constKSecPrivateKeyAttrs);

        valueBuilder.Add(IOSConstants.Preloaded.constKSecAttrKeyTypeRSA);
        valueBuilder.Add(keySize);
        valueBuilder.Add(privateKeyAttr);

        return NSDictionary.FromObjectsAndKeys(valueBuilder.ToArray(), keyBuilder.ToArray());
    }

public bool CreateNewRSAKey(int keySize)
    {
        if (!Delete())
        {
            return false;
        }

        var keyGenerationAttributes = BuildKeyPairAttributes(keySize);
        var privateKey = SecKey.CreateRandomKey(keyGenerationAttributes, out NSError errCode);

        if (privateKey == null || errCode != null)
        {
            //Handle error
            return false;
        }
        return true;
    }

You find the possible keys and values for the attributes in Apples Documentation. To get the values of the string constants you can use:

var handle = Dlfcn.dlopen(Constants.SecurityLibrary, 0);
constKSecAttrApplicationTag = Dlfcn.GetStringConstant(handle, "kSecAttrApplicationTag"); //replace with whatever constant you need
Dlfcn.dlclose(handle);

Here is the IOSConstants class with the used attributes:

class IOSConstants
{
    private static IOSConstants _singleton;

    public static IOSConstants Preloaded
    {
        get
        {
            if(_singleton == null)
            {
                _singleton = new IOSConstants();
            }
            return _singleton;
        }
    }

    public readonly NSString constKSecAttrKeyType;
    public readonly NSString constKSecAttrKeySize;
    public readonly NSString constKSecAttrKeyTypeRSA;
    public readonly NSString constKSecAttrIsPermanent;
    public readonly NSString constKSecAttrApplicationTag;
    public readonly NSString constKSecPrivateKeyAttrs;
    public readonly NSString constKSecClass;
    public readonly NSString constKSecClassKey;
    public readonly NSString constKSecPaddingPKCS1;
    public readonly NSString constKSecAccessibleWhenPasscodeSetThisDeviceOnly;
    public readonly NSString constKSecAttrAccessible;

    public IOSConstants()
    {
        var handle = Dlfcn.dlopen(Constants.SecurityLibrary, 0);

        try
        {
            constKSecAttrApplicationTag = Dlfcn.GetStringConstant(handle, "kSecAttrApplicationTag");
            constKSecAttrKeyType = Dlfcn.GetStringConstant(handle, "kSecAttrKeyType");
            constKSecAttrKeyTypeRSA = Dlfcn.GetStringConstant(handle, "kSecAttrKeyTypeRSA");
            constKSecAttrKeySize = Dlfcn.GetStringConstant(handle, "kSecAttrKeySizeInBits");
            constKSecAttrIsPermanent = Dlfcn.GetStringConstant(handle, "kSecAttrIsPermanent");
            constKSecPrivateKeyAttrs = Dlfcn.GetStringConstant(handle, "kSecPrivateKeyAttrs");
            constKSecClass = Dlfcn.GetStringConstant(handle, "kSecClass");
            constKSecClassKey = Dlfcn.GetStringConstant(handle, "kSecClassKey");
            constKSecPaddingPKCS1 = Dlfcn.GetStringConstant(handle, "kSecPaddingPKCS1");
            constKSecAccessibleWhenPasscodeSetThisDeviceOnly = Dlfcn.GetStringConstant(handle, "kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly");
            constKSecAttrAccessible = Dlfcn.GetStringConstant(handle, "kSecAttrAccessible");
        }
        finally
        {
            Dlfcn.dlclose(handle);
        }
    }
}

When you create the key pair with this methods, you can get the public key with SecKey.GetPublicKey().GetExternalRepresentation()

 private SecKey GetKeyFromKeyChain()
    {
        var foundKey = SecKeyChain.QueryAsConcreteType(
            new SecRecord(SecKind.Key)
            {
                ApplicationTag = KeyAlias
            }, out SecStatusCode errCode);

        if (foundKey == null || errCode != SecStatusCode.Success)
        {
            //Handle error
            return null;
        }
        return foundKey as SecKey;
    }

 public byte[] GetPublicKey()
    {
        NSError errCode = null;

        var foundKey = GetKeyFromKeyChain();
        var publicKey = foundKey?.GetPublicKey();
        var publicKeyExternalFormat = publicKey?.GetExternalRepresentation(out errCode);

        if (publicKeyExternalFormat == null || errCode != null)
        {
            //Handle error
            return null;
        }
        return publicKeyExternalFormat.ToArray();
    }

On my iPhone 5s the returned public key is a simple asn1 sequence, containing the modulus and the exponent, to get it work with bouncy castle i convert this to the pkcs#8 public key format.

 var pkcs8PublicKey = new DerSequence(
     new DerSequence(
         new DerObjectIdentifier("1.2.840.113549.1.1.1"),
         DerNull.Instance),
     new DerBitString(publicKeyFromKeyChain)
 ).GetDerEncoded();

EDIT

Using this attributes, iOS asks me for touch id every time i want to access the key

//in BuildKeyPairAttributes
keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrIsPermanent);
keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrApplicationTag);  
//constKSecAttrAccessControl = Dlfcn.GetStringConstant(handle, "kSecAttrAccessControl");
keyBuilder.Add(IOSConstants.Preloaded.constKSecAttrAccessControl);

valueBuilder.Add(NSNumber.FromBoolean(true));
valueBuilder.Add(KeyAlias);
valueBuilder.Add(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence));

NSDictionary privateKeyAttr = NSDictionary.FromObjectsAndKeys(valueBuilder.ToArray(), keyBuilder.ToArray());
15
  • Thanks for the reply :) However how to import IOSConstants? =/ Mar 29, 2018 at 14:27
  • IOSConstants is one of my classes, it just load all the constants using the piece of code i added some minutes ago.
    – MiSimon
    Mar 29, 2018 at 14:35
  • o.0 Wow nice... Many thanks! Could you please show the IOSContants class? I'm curious, now. Seems like your code is pretty clean, would like to see how you did it on IOSConstants :) Is "IOSConstants.Preloaded.const****" a method? You created a method to each constant? Mar 29, 2018 at 14:46
  • I edited my answer and added the IOSConstants class. (I know its not best practices to do that much work in the constructor :-) )
    – MiSimon
    Mar 29, 2018 at 14:53
  • Many thanks! Always learning :) Really thanks. Will try to implement your solution :) I'll give feedback as soon as i do it Mar 29, 2018 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.