Example #1
0
        public void CreateKeyPair()
        {
            DeleteKey();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2 &&
                Build.VERSION.SdkInt <= BuildVersionCodes.LollipopMr1)
            {
                var calendar = Calendar.GetInstance(_context.Resources.Configuration.Locale);
                var endDate  = Calendar.GetInstance(_context.Resources.Configuration.Locale);
                endDate.Add(CalendarField.Year, 20);
                //this API is obsolete after Android M, but I am supporting Android L
#pragma warning disable 618
                var builder = new KeyPairGeneratorSpec.Builder(_context)
#pragma warning restore 618
                              .SetAlias(_keyName).SetSerialNumber(BigInteger.One)
                              .SetSubject(new X500Principal($"CN={_keyName} CA Certificate"))
                              .SetStartDate(calendar.Time)
                              .SetEndDate(endDate.Time).SetKeySize(KeySize);
                keyGenerator.Initialize(builder.Build());
            }
            else if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                var builder =
                    new KeyGenParameterSpec.Builder(_keyName, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                    .SetBlockModes(KeyProperties.BlockModeEcb)
                    .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                    .SetRandomizedEncryptionRequired(false).SetKeySize(KeySize);
                keyGenerator.Initialize(builder.Build());
            }
            keyGenerator.GenerateKeyPair();
        }
Example #2
0
        // Generates keys for RSA signing
        public IxianKeyPair generateKeys(int keySize, bool skip_header = false)
        {
            KeyPair kp = null;

            try
            {
                KeyPairGenerator kpg = KeyPairGenerator.GetInstance("RSA");
                kpg.Initialize(keySize);
                kp = kpg.GenKeyPair();
                IxianKeyPair ixi_kp = new IxianKeyPair();
                ixi_kp.privateKeyBytes = rsaKeyToBytes(kp, true, skip_header);
                ixi_kp.publicKeyBytes  = rsaKeyToBytes(kp, false, skip_header);

                byte[] plain = Encoding.UTF8.GetBytes("Plain text string");
                if (!testKeys(plain, ixi_kp))
                {
                    return(null);
                }
                return(ixi_kp);
            }
            catch (Exception e)
            {
                Logging.warn(string.Format("Exception while generating signature keys: {0}", e.ToString()));
                return(null);
            }
        }
Example #3
0
        /// <exception cref="NoSuchAlgorithmException"/>
        public static KeyPair GenerateKeyPair(string algorithm)
        {
            KeyPairGenerator keyGen = KeyPairGenerator.GetInstance(algorithm);

            keyGen.Initialize(1024);
            return(keyGen.GenKeyPair());
        }
Example #4
0
        /// <summary>
        /// Creates a new public-private key pair. An already existing key will be deleted, so
        /// make sure to call <see cref="KeysExistInKeyStore"/> before.
        /// </summary>
        private void CreateKeyPairInKeyStore()
        {
            RemoveKeyFromKeyStore();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KeyStoreName);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2 &&
                Build.VERSION.SdkInt <= BuildVersionCodes.LollipopMr1)
            {
                Calendar startDateCalendar = Calendar.GetInstance(Locale.Default);
                startDateCalendar.Add(CalendarField.Year, -1);
                Calendar endDateCalendar = Calendar.GetInstance(Locale.Default);
                endDateCalendar.Add(CalendarField.Year, 100);
                string certificateName = string.Format("CN={0} CA Certificate", KeyAlias);

                // this API is obsolete after Android M, but we are supporting Android L
#pragma warning disable 618
                var builder = new KeyPairGeneratorSpec.Builder(_applicationContext)
                              .SetAlias(KeyAlias)
                              .SetSerialNumber(BigInteger.One)
                              .SetSubject(new X500Principal(certificateName))
                              .SetStartDate(startDateCalendar.Time)
                              .SetEndDate(endDateCalendar.Time)
                              .SetKeySize(KeySize);
#pragma warning restore 618

                keyGenerator.Initialize(builder.Build());
            }
            else if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                Calendar endDateCalendar = Calendar.GetInstance(Locale.Default);
                endDateCalendar.Add(CalendarField.Year, 100);

                var builder = new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                              .SetBlockModes(KeyProperties.BlockModeEcb)
                              .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                              .SetCertificateNotAfter(endDateCalendar.Time)
                              .SetKeySize(KeySize);
                keyGenerator.Initialize(builder.Build());
            }

            // Key generator is initialized, generate the key
            keyGenerator.GenerateKeyPair();
        }
        private void CreateNewKey(string alias)
        {
            KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Decrypt | KeyStorePurpose.Encrypt)
                                       .SetBlockModes(KeyProperties.BlockModeCbc)
                                       .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                                       .Build();

            KeyPairGenerator generator = KeyPairGenerator.GetInstance("RSA", "AndroidKeyStore");

            generator.Initialize(spec);

            generator.GenerateKeyPair();
        }
Example #6
0
File: DH.cs Project: shoff/ngit
 //    myKeyAgree=KeyAgreement.getInstance("DiffieHellman");
 /// <exception cref="System.Exception"></exception>
 public virtual byte[] GetE()
 {
     if (e == null)
     {
         DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g);
         myKpairGen.Initialize(dhSkipParamSpec);
         Sharpen.KeyPair myKpair = myKpairGen.GenerateKeyPair();
         myKeyAgree.Init(myKpair.GetPrivate());
         //    BigInteger x=((javax.crypto.interfaces.DHPrivateKey)(myKpair.getPrivate())).getX();
         e       = ((DHPublicKey)(myKpair.GetPublic())).GetY();
         e_array = e.GetBytes();
     }
     return(e_array);
 }
        // private
        // public
        /// <exception cref="System.Exception"></exception>
        public virtual void Init(int key_size)
        {
            KeyPairGenerator keyGen = KeyPairGenerator.GetInstance("DSA");

            keyGen.Initialize(key_size, new SecureRandom());
            Sharpen.KeyPair pair   = keyGen.GenerateKeyPair();
            PublicKey       pubKey = pair.GetPublic();
            PrivateKey      prvKey = pair.GetPrivate();

            x = ((DSAPrivateKey)prvKey).GetX().GetBytes();
            y = ((DSAPublicKey)pubKey).GetY().GetBytes();
            DSAParams @params = ((DSAKey)prvKey).GetParams();

            p = @params.GetP().GetBytes();
            q = @params.GetQ().GetBytes();
            g = @params.GetG().GetBytes();
        }
Example #8
0
        // private
        // public
        //  coefficient
        // exponent p
        // exponent q
        // prime p
        // prime q
        /// <exception cref="System.Exception"></exception>
        public virtual void Init(int key_size)
        {
            KeyPairGenerator keyGen = KeyPairGenerator.GetInstance("RSA");

            keyGen.Initialize(key_size, new SecureRandom());
            Sharpen.KeyPair pair   = keyGen.GenerateKeyPair();
            PublicKey       pubKey = pair.GetPublic();
            PrivateKey      prvKey = pair.GetPrivate();

            d  = ((RSAPrivateKey)prvKey).GetPrivateExponent().GetBytes();
            e  = ((RSAPublicKey)pubKey).GetPublicExponent().GetBytes();
            n  = ((RSAPrivateKey)prvKey).GetModulus().GetBytes();
            c  = ((RSAPrivateCrtKey)prvKey).GetCrtCoefficient().GetBytes();
            ep = ((RSAPrivateCrtKey)prvKey).GetPrimeExponentP().GetBytes();
            eq = ((RSAPrivateCrtKey)prvKey).GetPrimeExponentQ().GetBytes();
            p  = ((RSAPrivateCrtKey)prvKey).GetPrimeP().GetBytes();
            q  = ((RSAPrivateCrtKey)prvKey).GetPrimeQ().GetBytes();
        }
Example #9
0
        private static void GenerateKeyPair(Context context, String alias)
        {
            Calendar start = new GregorianCalendar();
            Calendar end   = new GregorianCalendar();

            end.Add(CalendarField.Year, 100);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                                        .SetAlias(alias)
                                        .SetSubject(new X500Principal("CN=" + alias))
                                        .SetSerialNumber(BigInteger.One)
                                        .SetStartDate(start.Time)
                                        .SetEndDate(end.Time)
                                        .Build();
            KeyPairGenerator gen = KeyPairGenerator.GetInstance("RSA", "AndroidKeyStore");

            gen.Initialize(spec);
            gen.GenerateKeyPair();
        }
Example #10
0
        public void CreateKey()
        {
            // Removes key if it already exists, no change otherwise
            DeleteKey();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);

            // Parameters affiliated with the Transformation settings used when making Cipher
            var builder = new KeyGenParameterSpec.Builder(_keyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                          .SetBlockModes(KeyProperties.BlockModeEcb)
                          .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                          .SetRandomizedEncryptionRequired(false).SetKeySize(KEY_SIZE);

            keyGenerator.Initialize(builder.Build());
            builder.Dispose();

            // Keys automattically added to KeyStore
            keyGenerator.GenerateKeyPair();
            keyGenerator.Dispose();
        }
        private void GenerateRSAKey()
        {
            // Generate a key pair for encryption
            Calendar start = Calendar.GetInstance(Locale.Default);
            Calendar end   = Calendar.GetInstance(Locale.Default);

#pragma warning disable CS0618 // Type or member is obsolete
            end.Add(Calendar.Year, 30);

            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(Android.App.Application.Context)
#pragma warning restore CS0618 // Type or member is obsolete
                                        .SetAlias(_secureStoredKeyAlias)
                                        .SetSubject(new X500Principal("CN=" + _secureStoredKeyAlias))
                                        .SetSerialNumber(BigInteger.Ten)
                                        .SetStartDate(start.Time)
                                        .SetEndDate(end.Time)
                                        .Build();
            KeyPairGenerator kpg = KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, _droidKeyStore);
            kpg.Initialize(spec);
            kpg.GenerateKeyPair();
        }
Example #12
0
        /// <summary>
        /// Create new RSA key pair for KeyStore instance
        /// </summary>
        /// <param name="alias">KeyStore instance alias</param>
        /// <param name="context">Root context</param>
        /// <returns>True/False = Created or not</returns>
        private static bool CreateNewRSAKeyPair(string alias, Context context)
        {
            try
            {
                Calendar start = Calendar.GetInstance(Java.Util.TimeZone.Default);
                Calendar end   = Calendar.GetInstance(Java.Util.TimeZone.Default);
                end.Add(CalendarField.Year, 100);
                KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                                            .SetAlias(alias)
                                            .SetSubject(new Javax.Security.Auth.X500.X500Principal("CN=CryptoTouch, O=Android Authority"))
                                            .SetSerialNumber(Java.Math.BigInteger.One)
                                            .SetStartDate(start.Time)
                                            .SetEndDate(end.Time)
                                            .Build();
                KeyPairGenerator generator = KeyPairGenerator.GetInstance("RSA", STORE_NAME);
                generator.Initialize(spec);
                _keyPair = generator.GenerateKeyPair();

                return(true);
            }
            catch (Exception ex) { Toast.MakeText(context, ex.Message, ToastLength.Long).Show(); return(false); }
        }
        /// <summary>
        /// Creates a new public-private key pair. An already existing key will be deleted, so
        /// make sure to call <see cref="KeysExistInKeyStore"/> before.
        /// </summary>
        private void CreateKeyPairInKeyStore()
        {
            RemoveKeyFromKeyStore();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KeyStoreName);

            // With Build.VERSION.SdkInt < BuildVersionCodes.M we would have to use an alternative
            // way, but Android 6 is our min version.
            Calendar endDateCalendar = Calendar.GetInstance(Locale.Default);

            endDateCalendar.Add(CalendarField.Year, 100);

            var builder = new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                          .SetBlockModes(KeyProperties.BlockModeEcb)
                          .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                          .SetCertificateNotAfter(endDateCalendar.Time)
                          .SetKeySize(KeySize);

            keyGenerator.Initialize(builder.Build());

            // Key generator is initialized, generate the key
            keyGenerator.GenerateKeyPair();
        }