コード例 #1
0
        KeyPair GetAsymmetricKeyPair()
        {
            // set that we generated keys on pre-m device.
            Preferences.Set(useSymmetricPreferenceKey, false, SecureStorage.Alias);

            var asymmetricAlias = $"{alias}.asymmetric";

            var privateKey = keyStore.GetKey(asymmetricAlias, null)?.JavaCast <IPrivateKey>();
            var publicKey  = keyStore.GetCertificate(asymmetricAlias)?.PublicKey;

            // Return the existing key if found
            if (privateKey != null && publicKey != null)
            {
                return(new KeyPair(publicKey, privateKey));
            }

            var originalLocale = Platform.GetLocale();

            try
            {
                // Force to english for known bug in date parsing:
                // https://issuetracker.google.com/issues/37095309
                Platform.SetLocale(Java.Util.Locale.English);

                // Otherwise we create a new key
                var generator = KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, androidKeyStore);

                var end       = DateTime.UtcNow.AddYears(20);
                var startDate = new Java.Util.Date();
#pragma warning disable CS0618 // Type or member is obsolete
                var endDate = new Java.Util.Date(end.Year, end.Month, end.Day);
#pragma warning restore CS0618 // Type or member is obsolete

#pragma warning disable CS0618
                var builder = new KeyPairGeneratorSpec.Builder(Platform.AppContext)
                              .SetAlias(asymmetricAlias)
                              .SetSerialNumber(Java.Math.BigInteger.One)
                              .SetSubject(new Javax.Security.Auth.X500.X500Principal($"CN={asymmetricAlias} CA Certificate"))
                              .SetStartDate(startDate)
                              .SetEndDate(endDate);

                generator.Initialize(builder.Build());
#pragma warning restore CS0618

                return(generator.GenerateKeyPair());
            }
            finally
            {
                Platform.SetLocale(originalLocale);
            }
        }