예제 #1
0
 public void Given()
 {
     _fs = new InMemoryFileSystem();
     var ks = new KeyStore<string>(_fs, new Settings(@"c:\db\raptile.db"));
     ks.Dispose();
     _dir = _fs.GetDirectory(@"c:\db");
 }
        /// <summary>
        /// Default constructor created or loads the store
        /// </summary>
        public SecureStorageImplementation()
        {
            // verify that password is set
            if (string.IsNullOrWhiteSpace(StoragePassword))
            {
                throw new Exception($"Must set StoragePassword");
            }

            StoragePasswordArray = StoragePassword.ToCharArray();

            // Instantiate store and protection
            _store = KeyStore.GetInstance(KeyStore.DefaultType);
            _passwordProtection = new KeyStore.PasswordProtection(StoragePasswordArray);

            // if store exists, load it from the file
            try
            {
                using (var stream = new IsolatedStorageFileStream(StorageFile, FileMode.Open, FileAccess.Read))
                {
                    _store.Load(stream, StoragePasswordArray);
                }
            }
            catch (Exception)
            {
                // this will happen for the first run. As no file is expected to be present
                _store.Load(null, StoragePasswordArray);
            }

        }
		public Cipher ProvidesCipher (KeyStore keyStore)
		{
			try {
				return Cipher.GetInstance ("AES/CBC/PKCS7Padding");
			} catch (NoSuchAlgorithmException e) {
				throw new RuntimeException ("Failed to get an instance of Cipher", e);
			} catch (NoSuchPaddingException e) {
				throw new RuntimeException ("Failed to get an instance of Cipher", e);
			}
		}
예제 #4
0
		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);
			fingerprintModule = new FingerprintModule(this);
			mKeyguardManager = fingerprintModule.ProvidesKeyguardManager (this);
			mKeyStore = fingerprintModule.ProvidesKeystore ();
			mKeyGenerator = fingerprintModule.ProvidesKeyGenerator ();
			mCipher = fingerprintModule.ProvidesCipher (mKeyStore);

			RequestPermissions (new [] { Manifest.Permission.UseFingerprint }, 0);
		}
예제 #5
0
		static void Save(string clientid, string service, KeyStore ks)
		{
			var context = global::Android.App.Application.Context;
			lock(fileLock)
			{
				using(var s = context.OpenFileOutput(clientid, FileCreationMode.Private))
				{
					ks.Store(s, service.ToCharArray());
				}
			}
		}
		public Cipher ProvidesCipher (KeyStore keyStore)
		{
			try {
				return Cipher.GetInstance (KeyProperties.KeyAlgorithmAes + "/"
					+ KeyProperties.BlockModeCbc + "/"
					+ KeyProperties.EncryptionPaddingPkcs7);
			} catch (NoSuchAlgorithmException e) {
				throw new RuntimeException ("Failed to get an instance of Cipher", e);
			} catch (NoSuchPaddingException e) {
				throw new RuntimeException ("Failed to get an instance of Cipher", e);
			}
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyVaultStorage"/> class.
        /// </summary>
        /// <param name="password">Password to use for encryption.</param>
        public KeyVaultStorage(char[] password)
        {
            this.keyStore = KeyStore.GetInstance(KeyStore.DefaultType);
            this.protection = new KeyStore.PasswordProtection(password);

            if (File.FileExists(StorageFile))
            {
                using (var stream = new IsolatedStorageFileStream(StorageFile, FileMode.Open, FileAccess.Read, File))
                {
                    this.keyStore.Load(stream, password);
                }
            }
            else
            {
                this.keyStore.Load(null, password);
            }
        }
예제 #8
0
파일: Tests.cs 프로젝트: flq/Raptile
        public void RemoveKeyTest()
        {
            var path = new Settings("remove.dat");
            var rdb = new KeyStore<long>(_fileSystem, path);
            rdb.Set(1, "a");
            rdb.Set(2, "b");
            rdb.Dispose();

            rdb = new KeyStore<long>(_fileSystem, path);
            rdb.Remove(1L);
            rdb.Dispose();

            rdb = new KeyStore<long>(_fileSystem, path);
            string data;
            bool result = rdb.Get(1, out data);
            if (result)
                Assert.Fail();
        }
예제 #9
0
		public AndroidAccountStore (Context context)
		{
			this.context = context;

			ks = KeyStore.GetInstance (KeyStore.DefaultType);

			prot = new KeyStore.PasswordProtection (Password);

			try {
				lock (fileLock) {
					using (var s = context.OpenFileInput (FileName)) {
						ks.Load (s, Password);
					}
				}
			}
			catch (FileNotFoundException) {
				//ks.Load (null, Password);
				LoadEmptyKeyStore (Password);
			}
		}
예제 #10
0
 /// <summary>
 /// Work around Bug https://bugzilla.xamarin.com/show_bug.cgi?id=6766
 /// </summary>
 static void LoadEmptyKeyStore(KeyStore ks, char[] password)
 {
     if (id_load_Ljava_io_InputStream_arrayC == IntPtr.Zero)
     {
         id_load_Ljava_io_InputStream_arrayC = JNIEnv.GetMethodID(ks.Class.Handle, "load", "(Ljava/io/InputStream;[C)V");
     }
     IntPtr intPtr = IntPtr.Zero;
     IntPtr intPtr2 = JNIEnv.NewArray(password);
     JNIEnv.CallVoidMethod(ks.Handle, id_load_Ljava_io_InputStream_arrayC, new JValue[]
         {
             new JValue (intPtr),
             new JValue (intPtr2)
         });
     JNIEnv.DeleteLocalRef(intPtr);
     if (password != null)
     {
         JNIEnv.CopyArray(intPtr2, password);
         JNIEnv.DeleteLocalRef(intPtr2);
     }
 }
예제 #11
0
        public AndroidKeyStoreStorageService(ISettings settings)
        {
            _oldAndroid = Build.VERSION.SdkInt < BuildVersionCodes.M;
            _rsaMode    = _oldAndroid ? "RSA/ECB/PKCS1Padding" : "RSA/ECB/OAEPWithSHA-1AndMGF1Padding";

            _settings = settings;

            _keyStore = KeyStore.GetInstance(AndroidKeyStore);
            _keyStore.Load(null);

            try
            {
                GenerateStoreKey(true);
            }
            catch
            {
                GenerateStoreKey(false);
            }

            GenerateAesKey();
        }
예제 #12
0
        public void Test_KeyStore()
        {
            Random random = new Random();

            byte[] passwordBytes = new byte[random.Next() % 256];
            random.NextBytes(passwordBytes);
            string password = Convert.ToBase64String(passwordBytes);

            PrivateKey      privateKey = PrivateKey.Random();
            ExternalAddress address    = Addresser.Create(privateKey);

            KeyStore keyStore = KeyStore.Create(privateKey, address);
            string   fileName = keyStore.Store(password);

            keyStore = KeyStore.Load(password, fileName);

            File.Delete(fileName);

            Assert.AreEqual(privateKey, keyStore.PrivateKey);
            Assert.AreEqual(address, keyStore.Address);
        }
예제 #13
0
        public async Task CreatePrivateKeyWithGivenPrivateKey()
        {
            // FIXME: passphrase로 "passphrase" 대신 랜덤 문자열을 사용하면 좋을 것 같습니다.
            var privateKey    = new PrivateKey();
            var privateKeyHex = ByteUtil.Hex(privateKey.ByteArray);
            var result        = await ExecuteQueryAsync(
                $"mutation {{ keyStore {{ createPrivateKey(passphrase: \"passphrase\", privateKey: \"{privateKeyHex}\") {{ hex publicKey {{ address }} }} }} }}");

            var privateKeyResult = result.Data.As <Dictionary <string, object> >()["keyStore"]
                                   .As <Dictionary <string, object> >()["createPrivateKey"]
                                   .As <Dictionary <string, object> >();
            var createdPrivateKeyHex = privateKeyResult
                                       .As <Dictionary <string, object> >()["hex"].As <string>();
            var createdPrivateKeyAddress = privateKeyResult
                                           .As <Dictionary <string, object> >()["publicKey"]
                                           .As <Dictionary <string, object> >()["address"].As <string>();

            Assert.Equal(privateKey, new PrivateKey(ByteUtil.ParseHex(createdPrivateKeyHex)));
            Assert.Contains(KeyStore.List(),
                            t => t.Item2.Address.ToString() == createdPrivateKeyAddress);
        }
        public SecureStorage_Droid()
        {
            _keyStore = KeyStore.GetInstance(_droidKeyStore);
            _keyStore.Load(null);

            // Check if the RSA Key for encryptiong the stored credentials already exists
            // Typically, this needs to be created when the database and its corresponding keys is generated on first App launch
            if (!_keyStore.ContainsAlias(_secureStoredKeyAlias))
            {
                // We have to check the API level to avoid using deprecated methods when not needed
                if ((int)Build.VERSION.SdkInt > 22)
                {
                    GenerateAESKey_New();
                }
                else
                {
                    GenerateRSAKey();
                    GenerateAESKey_Depr();
                }
            }
        }
        JwtSecurityToken CreateJwtSecurityToken(User user)
        {
            var claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Jti, Config.Id),
                new Claim(JwtRegisteredClaimNames.Sub, user.Name),
                new Claim(ClaimTypes.Sid, Config.Id),
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Role, user.Role)
            };

            var token = new JwtSecurityToken(
                issuer: Config.Issuer,
                audience: Config.Audience,
                claims: claims,
                expires: DateTime.UtcNow.AddDays(7),
                signingCredentials: new SigningCredentials(KeyStore.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)
                );

            return(token);
        }
예제 #16
0
        /// <summary>
        /// Work around Bug https://bugzilla.xamarin.com/show_bug.cgi?id=6766
        /// </summary>
        static void LoadEmptyKeyStore(KeyStore ks, char[] password)
        {
            if (id_load_Ljava_io_InputStream_arrayC == IntPtr.Zero)
            {
                id_load_Ljava_io_InputStream_arrayC = JNIEnv.GetMethodID(ks.Class.Handle, "load", "(Ljava/io/InputStream;[C)V");
            }
            IntPtr intPtr  = IntPtr.Zero;
            IntPtr intPtr2 = JNIEnv.NewArray(password);

            JNIEnv.CallVoidMethod(ks.Handle, id_load_Ljava_io_InputStream_arrayC, new JValue[]
            {
                new JValue(intPtr),
                new JValue(intPtr2)
            });
            JNIEnv.DeleteLocalRef(intPtr);
            if (password != null)
            {
                JNIEnv.CopyArray(intPtr2, password);
                JNIEnv.DeleteLocalRef(intPtr2);
            }
        }
 private void CreateStore()
 {
     this.context = Android.App.Application.Context;
     ks           = KeyStore.GetInstance(KeyStore.DefaultType);
     prot         = new KeyStore.PasswordProtection(Password);
     try
     {
         lock (fileLock)
         {
             using (var s = context.OpenFileInput(FileName))
             {
                 ks.Load(s, Password);
             }
         }
     }
     catch (Java.IO.FileNotFoundException)
     {
         //ks.Load (null, Password);
         LoadEmptyKeyStore(Password);
     }
 }
        public static KeyStore <Pbkdf2Params> MapDTOToModel(KeyStorePbkdf2DTO dto)
        {
            var pbdk2KeyStore = new KeyStore <Pbkdf2Params>();

            pbdk2KeyStore.Address                = dto.address;
            pbdk2KeyStore.Id                     = dto.id;
            pbdk2KeyStore.Version                = dto.version;
            pbdk2KeyStore.Crypto                 = new CryptoInfo <Pbkdf2Params>();
            pbdk2KeyStore.Crypto.Cipher          = dto.crypto.cipher;
            pbdk2KeyStore.Crypto.CipherText      = dto.crypto.cipherText;
            pbdk2KeyStore.Crypto.Kdf             = dto.crypto.kdf;
            pbdk2KeyStore.Crypto.Mac             = dto.crypto.mac;
            pbdk2KeyStore.Crypto.Kdfparams       = new Pbkdf2Params();
            pbdk2KeyStore.Crypto.Kdfparams.Count = dto.crypto.kdfparams.c;
            pbdk2KeyStore.Crypto.Kdfparams.Prf   = dto.crypto.kdfparams.prf;
            pbdk2KeyStore.Crypto.Kdfparams.Dklen = dto.crypto.kdfparams.dklen;
            pbdk2KeyStore.Crypto.Kdfparams.Salt  = dto.crypto.kdfparams.salt;
            pbdk2KeyStore.Crypto.CipherParams    = new CipherParams();
            pbdk2KeyStore.Crypto.CipherParams.Iv = dto.crypto.cipherparams.iv;
            return(pbdk2KeyStore);
        }
예제 #19
0
        public void WhenCalculateBalance0PTCSLeft()
        {
            RemoveBlockChain();
            var serviceProvider   = BuildServiceProvider();
            var transactionHelper = serviceProvider.GetService <ITransactionHelper>();
            var blockChainFactory = serviceProvider.GetService <IBlockChainFactory>();
            var blockChainStore   = serviceProvider.GetService <IBlockChainStore>();

            blockChainStore.Switch(_network);
            var blockChain                   = blockChainStore.GetBlockChain(); // Get the genesis block.
            var genesisBlock                 = blockChain.GetCurrentBlock();
            var firstTransaction             = genesisBlock.Transactions.First() as BcBaseTransaction;
            var firstTransactionOut          = firstTransaction.TransactionOut.First();
            var genesisKey                   = KeyStore.GetGenesisKey();
            var genesisAdr                   = new BlockChainAddress(_scriptTypes, _network, genesisKey); // Create block chain address.
            var destinationBlockChainAddress = GenerateBlockChainAddress();

            var signature     = genesisKey.GetSignature(); // Create the script.
            var scriptBuilder = new ScriptBuilder();
            var genesisScript = scriptBuilder
                                .New()
                                .AddToStack(signature)
                                .AddToStack(genesisKey.GetPublicKey())
                                .Build();
            var destinationScript = Script.CreateP2PKHScript(destinationBlockChainAddress.PublicKeyHash);
            var destGenesisScript = Script.CreateP2PKHScript(genesisKey.GetPublicKeyHashed());

            var transactionBuilder      = new TransactionBuilder();
            var noneCoinBaseTransaction = transactionBuilder // ADD GENESIS (10 BTC) => DESTINATION TRANSACTION.
                                          .NewNoneCoinbaseTransaction()
                                          .Spend(firstTransaction, 0, genesisScript.Serialize())
                                          .AddOutput(2, destinationScript)
                                          .Build();

            var balance         = transactionHelper.CalculateBalance(noneCoinBaseTransaction, new[] { genesisAdr }, _network);
            var receiverBalance = transactionHelper.CalculateBalance(noneCoinBaseTransaction, new[] { destinationBlockChainAddress }, _network);

            Assert.IsTrue(balance == 0);
            Assert.IsTrue(receiverBalance == 2);
        }
예제 #20
0
        public static Dictionary <X509Certificate2, System.Exception> ValidateCacerts()
        {
            var dic    = new Dictionary <X509Certificate2, System.Exception>();
            var jstore = KeyStore.getInstance("jks");

            jstore.load(null);
            var cf = java.security.cert.CertificateFactory.getInstance("X509");

            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            Dictionary <string, string> aliases = new Dictionary <string, string>();

            foreach (X509Certificate2 cert in store.Certificates)
            {
                try
                {
                    dic[cert] = null;
                    if (!cert.HasPrivateKey)
                    {
                        // the alias must be unique, otherwise we overwrite the previous certificate with that alias
                        string alias  = cert.Subject;
                        int    unique = 0;
                        while (aliases.ContainsKey(alias))
                        {
                            alias = cert.Subject + " #" + (++unique);
                        }
                        aliases.Add(alias, null);
                        //jstore.setCertificateEntry(alias, cf.generateCertificate(new ByteArrayInputStream(cert.RawData)));
                        cf.generateCertificate(new ByteArrayInputStream(cert.RawData));
                    }
                }
                catch (System.Exception ex)
                {
                    dic[cert] = ex;
                }
            }
            store.Close();
            return(dic);
        }
예제 #21
0
        public WalletAccount(Near near, string appKeyPrefix, IExternalAuthService authService, IExternalAuthStorage authStorage)
        {
            _networkId     = near.Config.NetworkId;
            _walletBaseUrl = near.Config.WalletUrl;
            appKeyPrefix   = string.IsNullOrEmpty(appKeyPrefix) || string.IsNullOrWhiteSpace(appKeyPrefix)
                ? "default"
                : appKeyPrefix;
            _authDataKey = $"{appKeyPrefix}{LocalStorageKeySuffix}";
            _keyStore    = (near.Connection.Signer as InMemorySigner).KeyStore;
            _authService = authService;
            _authStorage = authStorage;


            if (_authStorage.HasKey(_authDataKey))
            {
                _authData.AccountId = _authStorage.GetValue(_authDataKey);
            }
            else
            {
                _authData.AccountId = null;
            }
        }
        private IKey GetKey(string alias)
        {
            var keyStore = KeyStore.GetInstance(KeyStoreType);

            keyStore.Load(null);

            if (!keyStore.ContainsAlias(alias))
            {
                var generator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, KeyStoreType);
                generator.Init(new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                               .SetBlockModes(KeyProperties.BlockModeGcm)
                               .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone)
                               .SetRandomizedEncryptionRequired(false)
                               .Build());

                generator.GenerateKey();
            }

            var key = keyStore.GetKey(alias, null);

            return(key);
        }
        public CertificatePinning()
        {
            try {
                byte[] keyStoreBytes = Base64.Decode("H4sICIgmj1QAA2RlZmF1bHRfY2xpZW50X3RydXN0c3RvcmUuYmtzAN2aB1hUSbbHu5scJYPEBsnxNjlKziAgOSg0uQlNBgkiGVGyIogEQQQkqICIZBBQkSw5KxkRyQiI+BpBZ5xxxp19b+ftbn8fH9x7q4qqW+d3zv+cahAIBAaBQGRZ6Z6OVGc7OSWfRLZm21bvX5JmaQSBsFjBIIiQIKoNbBL3Fivo8INhxCsEiIFAEBkgBCIJhIDvQohcq2boiIY5BB+LvvRHa6+qBwgwcTgjVCI+EIDBEAwQYA7DA3Aw0fTRMUkh+rowSoD88AKXlNDAxh2hi7BDckNVkVa8MBFA6PABHimvvBPcwwMqANX2snRCWEG13RHOcHdfqLyNuyfCFmEF90S4IKGyXp72Lu4IT1+AnpJATBiA8YsBXz4mlAT8ooAo6oaAkJiQmMm/fgLBmb9eMxgDhBYcAwKCoyDBwaBWM+OMdZorYLJHRJPoMqPThg8cFGXiwvDxegSGh4m73kOMGFg+cOYrYBS8Q2O4cCnjWmUqqODUxYGi8GwrxefubO2bGs+83F6JrWjJrXpN4sY/i4W6pJzYKTpl7sohnNMaMV+SCm3TvRs+L1V3MfWAWVFgzJt8+US2m7WGDW+wvWIeBA0MAv9mS9BQ86rWIOHq4mYFaZGRjud+3MclDove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577kKpYopgtz2/CYNY/2ouQVdM9q36auWFHh5reb4qxNPvTsffHBY35PNzRYga531s+rNsBTpD7fJIJzTZfakOU9Homv6nHs+VFWC/P4V+0rD5D9M0onJbjQWJmJ/kOZrLT2YMcm0nhhl1Iq4KegtbDjeTc7XUnyJnEHE0uN037x5JyXaqNAe1+h9CxxzevM4ZDWe1FsTUnp8C5fyhvJTTLxYeG33PNuUq+kaB+86tvO9kvukOp4X1aVbNQIyYa8PmdypIqXTjgj5FAvEcSg9pJcSGhG1pKBSK557rOM08cByCdxNz3zgF0dCTWL/5KPtTTIyRbP78/cRlMFcJiKt5zk3n01lmendytUDda2uNT5PAaglhClG7yDffioufTqyAlEmvdKwVgYr1qJ9o5X24AR++ocLBEObQgZBIxXOlHHp9MHWbw5aFKuKHStx/c5oqYe9V1+7OE4MqsDje/kgd8n78wklKwDo8r7rc1X0fwBxS2vGpDgAAA==", 0);

                KeyStore keyStore         = KeyStore.GetInstance("BKS");
                System.IO.MemoryStream ms = new System.IO.MemoryStream(keyStoreBytes);
                GZIPInputStream        keyStoreInputStream = new GZIPInputStream(ms);
                //var readbytes = keyStoreInputStream.ToArray<byte>();

                List <byte> values = new List <byte>();

                bool notdone = true;
                while (notdone)
                {
                    var input = keyStoreInputStream.Read();
                    if (input < 0 || input > 255)
                    {
                        break;
                    }
                    values.Add((byte)input);
                }
                try {
                    keyStore.Load(new System.IO.MemoryStream(values.ToArray()), null);
                } finally {
                    keyStoreInputStream.Close();
                }
                TRUST_STORE = keyStore;

                String algorithm = TrustManagerFactory.DefaultAlgorithm;
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.GetInstance(algorithm);
                trustManagerFactory.Init(keyStore);

                SSLContext context = SSLContext.GetInstance("TLS");
                context.Init(null, trustManagerFactory.GetTrustManagers(), null);
                SSL_CONTEXT = context;
            } catch (Exception e) {
            }
        }
        public static KeyStore <ScryptParams> MapDTOToModel(KeyStoreScryptDTO dto)
        {
            var scryptKeyStore = new KeyStore <ScryptParams>();

            scryptKeyStore.Address                = dto.address;
            scryptKeyStore.Id                     = dto.id;
            scryptKeyStore.Version                = dto.version;
            scryptKeyStore.Crypto                 = new CryptoInfo <ScryptParams>();
            scryptKeyStore.Crypto.Cipher          = dto.crypto.cipher;
            scryptKeyStore.Crypto.CipherText      = dto.crypto.cipherText;
            scryptKeyStore.Crypto.Kdf             = dto.crypto.kdf;
            scryptKeyStore.Crypto.Mac             = dto.crypto.mac;
            scryptKeyStore.Crypto.Kdfparams       = new ScryptParams();
            scryptKeyStore.Crypto.Kdfparams.R     = dto.crypto.kdfparams.r;
            scryptKeyStore.Crypto.Kdfparams.N     = dto.crypto.kdfparams.n;
            scryptKeyStore.Crypto.Kdfparams.P     = dto.crypto.kdfparams.p;
            scryptKeyStore.Crypto.Kdfparams.Dklen = dto.crypto.kdfparams.dklen;
            scryptKeyStore.Crypto.Kdfparams.Salt  = dto.crypto.kdfparams.salt;
            scryptKeyStore.Crypto.CipherParams    = new CipherParams();
            scryptKeyStore.Crypto.CipherParams.Iv = dto.crypto.cipherparams.iv;
            return(scryptKeyStore);
        }
예제 #25
0
        public async Task RevokePrivateKey()
        {
            var privateKey = new PrivateKey();
            var passphrase = "";

            var protectedPrivateKey = ProtectedPrivateKey.Protect(privateKey, passphrase);

            KeyStore.Add(protectedPrivateKey);

            var address = privateKey.ToAddress();

            var result = await ExecuteQueryAsync(
                $"mutation {{ keyStore {{ revokePrivateKey(address: \"{address.ToHex()}\") {{ address }} }} }}");

            var revokedPrivateKeyAddress = result.Data.As <Dictionary <string, object> >()["keyStore"]
                                           .As <Dictionary <string, object> >()["revokePrivateKey"]
                                           .As <Dictionary <string, object> >()["address"].As <string>();

            Assert.DoesNotContain(KeyStore.List(),
                                  t => t.Item2.Address.ToString() == revokedPrivateKeyAddress);
            Assert.Equal(address.ToString(), revokedPrivateKeyAddress);
        }
예제 #26
0
        public void RefreshItems()
        {
            _listItems.Clear();
            foreach (String alias in KeyStore.Aliases)
            {
                KeyStoreEntryType entryType;
                if (KeyStore.IsCertificateEntry(alias))
                {
                    entryType = KeyStoreEntryType.TrustCertEntry;
                }
                else if (KeyStore.IsKeyEntry(alias) && KeyStore.GetCertificateChain(alias) != null && KeyStore.GetCertificateChain(alias).Length != 0)
                {
                    entryType = KeyStoreEntryType.KeyPairEntry;
                }
                else
                {
                    entryType = KeyStoreEntryType.KeyEntry;
                }

                _listItems.Add(new ListItemEntry(entryType, alias, KeyStore.GetCertificate(alias).Certificate));
            }
        }
예제 #27
0
        public async void StoredSuccessfully()
        {
            var calledBack = false;

            var fileServiceMock = new Mock <IFileService>();

            fileServiceMock.Setup(x => x.Exists(It.IsAny <string>())).Returns(false);
            fileServiceMock.Setup(x => x.WriteAllText(It.IsAny <string>(), It.IsAny <string>()))
            .Callback((string path, string json) =>
            {
                var obj = JObject.Parse(json);
                Assert.Equal("abc123", obj["thehost"].Value <string>());
                calledBack = true;
            });

            var fileService = fileServiceMock.Object;

            var keyStore = new KeyStore(fileService);
            await keyStore.StoreKeyAsync("thehost", "abc123");

            Assert.True(calledBack);
        }
예제 #28
0
        protected List <T> GetStoredAccounts <T>(KeyStoreTypes keyStoreType, int chainId) where T : KeyStore
        {
            var result = new List <T>();
            var path   = Path.Combine(_accountsPath, keyStoreType.ToString().ToLower());
            var files  = _storage.GetFiles(path, "*.*");

            foreach (var file in files)
            {
                try
                {
                    var ext = file.Extension;
                    if (ext != ".keystore")
                    {
                        continue;
                    }

                    var store = KeyStore.Restore <T>(_storage.ReadFileText(Path.Combine(path, file.Name)));
                    if (chainId > 0)
                    {
                        if (store.ChainId != chainId)
                        {
                            continue;
                        }
                    }
                    if (store.KeyStoreType != keyStoreType)
                    {
                        continue;
                    }

                    result.Add(store);
                }
                catch (Exception ex)
                {
                    Log.IgnoreException(ex, this);
                }
            }

            return(result);
        }
예제 #29
0
        protected override KeyStore ConfigureKeyStore(KeyStore keyStore)
        {
            if (_keyStore != null)
            {
                return(_keyStore);
            }

            _keyStore = KeyStore.GetInstance(KeyStore.DefaultType);
            _keyStore.Load(null, null);

            var cff = CertificateFactory.GetInstance("X.509");

            Certificate cert;

            // Add your Certificate to the Assets folder and address it here by its name
            using (var certStream = Application.Context.Assets.Open("google-com.cert"))
                cert = cff.GenerateCertificate(certStream);

            _keyStore.SetCertificateEntry("TrustedCert", cert);

            return(_keyStore);
        }
        public override byte[] Decrypt(byte[] encryptedBytes, byte[] iv, string keyName = null)
        {
            var key = KeyStore.GetKey(keyName ?? PublicKeyName);

            using (var aes = Aes.Create())
            {
                aes.Key  = Encoding.UTF8.GetBytes(key);
                aes.IV   = iv;
                aes.Mode = CipherMode.CBC;

                var decrypter = aes.CreateDecryptor(aes.Key, aes.IV);
                using (var ms = new MemoryStream(encryptedBytes))
                {
                    using (var cs = new CryptoStream(ms, decrypter, CryptoStreamMode.Read))
                        using (var sr = new StreamReader(cs))
                        {
                            var value = sr.ReadToEnd();
                            return(System.Text.Encoding.UTF8.GetBytes(value));
                        }
                }
            }
        }
        /// <summary>
        /// Remove a user from token cache.
        /// </summary>
        /// <param name="account"></param>
        /// <param name="tokenCache">This parameter is no longer used. However to keep the API unchanged it's not removed.</param>
        public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache)
        {
            if (account != null && !string.IsNullOrEmpty(account.Id) && !string.IsNullOrWhiteSpace(account.Type))
            {
                switch (account.Type)
                {
                case AzureAccount.AccountType.AccessToken:
                    account.SetProperty(AzureAccount.Property.AccessToken, null);
                    account.SetProperty(AzureAccount.Property.GraphAccessToken, null);
                    account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, null);
                    break;

                case AzureAccount.AccountType.ManagedService:
                    account.SetProperty(AzureAccount.Property.MSILoginUri, null);
                    break;

                case AzureAccount.AccountType.ServicePrincipal:
                    try
                    {
                        KeyStore.DeleteKey(new ServicePrincipalKey(AzureAccount.Property.ServicePrincipalSecret,
                                                                   account.Id, account.GetTenants().FirstOrDefault()));
                        KeyStore.DeleteKey(new ServicePrincipalKey(AzureAccount.Property.CertificatePassword,
                                                                   account.Id, account.GetTenants().FirstOrDefault()));
                    }
                    catch
                    {
                        // make best effort to remove credentials
                    }

                    RemoveFromTokenCache(account);
                    break;

                case AzureAccount.AccountType.User:
                    RemoveFromTokenCache(account);
                    break;
                }
            }
        }
예제 #32
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_main);

            var attraction = Intent.GetStringExtra(EXTRA_ATTRACTION);

            if (savedInstanceState == null)
            {
                SupportFragmentManager.BeginTransaction()
                .Add(Resource.Id.container, DetailFragment.CreateInstance(attraction))
                .Commit();
            }

            fingerprintModule = new FingerprintModule(this);
            mKeyguardManager  = fingerprintModule.ProvidesKeyguardManager(this);
            mKeyStore         = fingerprintModule.ProvidesKeystore();
            mKeyGenerator     = fingerprintModule.ProvidesKeyGenerator();
            mCipher           = fingerprintModule.ProvidesCipher(mKeyStore);

            RequestPermissions(new[] { Manifest.Permission.UseFingerprint }, FINGERPRINT_PERMISSION_REQUEST_CODE);
        }
예제 #33
0
		public KeyStoreAccess()
		{
			filename = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "pseadata");
			keyStore = KeyStore.GetInstance(KeyStore.DefaultType);

			Java.IO.File fileTest = new Java.IO.File(filename);

			// if an existing keystore is there then use it. Otherwise, create a new,
			// empty keystore
			if (fileTest.Exists() && fileTest.IsFile && fileTest.CanRead() && fileTest.CanWrite())
			{
				//FileInputStream file = new FileInputStream(filename);
				using (System.IO.FileStream file = new FileStream(filename, FileMode.Open))
				{
					keyStore.Load(file, Password.GetPassword());
					file.Close();
				}
			}
			else
			{
				keyStore.Load(null, Password.GetPassword());
			}
		}
        public KeyStoreAccess()
        {
            filename = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "pseadata");
            keyStore = KeyStore.GetInstance(KeyStore.DefaultType);

            Java.IO.File fileTest = new Java.IO.File(filename);

            // if an existing keystore is there then use it. Otherwise, create a new,
            // empty keystore
            if (fileTest.Exists() && fileTest.IsFile && fileTest.CanRead() && fileTest.CanWrite())
            {
                //FileInputStream file = new FileInputStream(filename);
                using (System.IO.FileStream file = new FileStream(filename, FileMode.Open))
                {
                    keyStore.Load(file, Password.GetPassword());
                    file.Close();
                }
            }
            else
            {
                keyStore.Load(null, Password.GetPassword());
            }
        }
        private static void InitializePrivateKey()
        {
            if (!_HasKeyStore)
            {
                return;
            }

            var keyStore = KeyStore.GetInstance("AndroidKeyStore");

            keyStore.Load(null);
            var entry = keyStore.GetEntry(Alias, null);

            if (entry != null && entry is KeyStore.SecretKeyEntry)
            {
                return;
            }

            var keyBuilder = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore");
            var spec       = new KeyGenParameterSpec.Builder(Alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt).SetBlockModes(KeyProperties.BlockModeCbc).SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7).Build();

            keyBuilder.Init(spec);
            keyBuilder.GenerateKey();
        }
예제 #36
0
        public void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                if (_passProtection != null)
                {
                    _passProtection.Dispose();
                    _passProtection = null;
                }
                if (_keyStore != null)
                {
                    _keyStore.Dispose();
                    _keyStore = null;
                }
            }

            _disposed = true;
        }
예제 #37
0
        public static void Main(string[] args)
        {
            Context ctx = new Context();

            KeyStore store = ctx.KeyStore;

            Key[] publickeys = store.GetKeyList("", false);
            Key[] secretkeys = store.GetKeyList("", true);

            Console.WriteLine("Public PGP keys currently saved in your store:");
            foreach (Key key in publickeys)
            {
                Console.WriteLine("Key " + key.Fingerprint);
                Console.WriteLine("\tUser: {0}\n", key.Uid.ToString());
            }

            Console.WriteLine("\nSecret PGP keys currently saved in your store:");
            foreach (Key key in secretkeys)
            {
                Console.WriteLine("Key " + key.Fingerprint);
                Console.WriteLine("\tUser: {0}\n", key.Uid.ToString());
            }
        }
예제 #38
0
        public static void ExportDemo(string path, string userId, int ID)
        {
            // initialize the KeyStore
            KeyStore ks = new KeyStore(@path, "changeit");

            // should the exported files be ASCII or binary
            bool asciiArmored = true;

            // export public key having the specified userId
            // all public sub keys are exported too



            ks.ExportPublicKey(@"C:/Users/Dua'a-Orcas/Desktop/WebApplication1/WebApplication1/WebApplication1/PageStudents/Sig/" + ID + ".asc", userId, asciiArmored);

            // export secret key having the specified userId, this is usually our own key
            // all secret sub keys are exported too
            ks.ExportPrivateKey(@"C:/Users/Dua'a-Orcas/Desktop/WebApplication1/WebApplication1/WebApplication1/PageStudents/Sig/" + ID + "pr" + ".asc", userId, asciiArmored);

            // export both public and secret key with all sub keys in one file
            // the file is in ASCII armored format by default
            // ks.ExportKeyRing(@"DataFiles\keypair.asc", "*****@*****.**");
        }
예제 #39
0
        public KeyStore cargarCertificado(string claveCertificado, long codigoEmisor, byte[] certificado)
        {
            KeyStore keyStore = (KeyStore)null;

            try
            {
                keyStore = KeyStore.getInstance("PKCS12");
            }
            catch (Exception ex)
            {
                int num = (int)XtraMessageBox.Show(" Error-->" + ex.ToString());
            }
            try
            {
                InputStream myInputStream = new ByteArrayInputStream(certificado);
                keyStore.load(myInputStream, claveCertificado.ToArray <char>());
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString());
            }
            return(keyStore);
        }
예제 #40
0
        public PasswordStorage(string fileName, char[] passkey)
        {
            this.filename = fileName;
            this.PassKey = passkey;

            this.keystore = KeyStore.GetInstance (KeyStore.DefaultType);
            this.protection = new KeyStore.PasswordProtection (this.PassKey);

            if (File.Exists (this.filename))
            {
                lock (this.locker)
                {
                    using (var stream = new FileStream (fileName, FileMode.Open))
                    {
                        keystore.Load (stream, passkey);
                    }
                }
            } 
            else
            {
                keystore.Load (null, passkey);
            }
        }
예제 #41
0
        public AndroidKeyStoreStorageService()
        {
            _oldAndroid = Build.VERSION.SdkInt < BuildVersionCodes.M;
            _rsaMode    = _oldAndroid ? "RSA/ECB/PKCS1Padding" : "RSA/ECB/OAEPWithSHA-1AndMGF1Padding";

            _settings = ServiceContainer.Resolve <SettingsShim>("settingsShim");

            _keyStore = KeyStore.GetInstance(AndroidKeyStore);
            _keyStore.Load(null);

            /*
             * try
             * {
             *  GenerateStoreKey(true);
             * }
             * catch
             * {
             *  GenerateStoreKey(false);
             * }
             *
             * GenerateAesKey();
             */
        }
예제 #42
0
        private X509Certificate _LoadCertificate(string path, string password, out PrivateKey privateKey, out Provider provider)
        {
            X509Certificate certificate = null;

            provider   = null;
            privateKey = null;

            KeyStore ks = KeyStore.getInstance("PKCS12");

            ks.load(new BufferedInputStream(new FileInputStream(path)), password.ToCharArray());
            IPKStoreManager storeManager = new KSStore(ks, new PassStoreKS(password));
            List            certificates = storeManager.getSignCertificates();

            if (certificates.size() == 1)
            {
                certificate = (X509Certificate)certificates.get(0);
                privateKey  = storeManager.getPrivateKey(certificate);
                provider    = storeManager.getProvider(certificate);
                return(certificate);
            }

            return(certificate);
        }
		/// <summary>
		/// Configures the key store. The <paramref name="keyStore"/> parameter is set to instance of <see cref="KeyStore"/>
		/// created using the <see cref="KeyStore.DefaultType"/> type and with populated with certificates provided in the <see cref="TrustedCerts"/>
		/// property. AndroidClientHandler implementation simply returns the instance passed in the <paramref name="keyStore"/> parameter
		/// </summary>
		/// <returns>The key store.</returns>
		/// <param name="keyStore">Key store to configure.</param>
		protected virtual KeyStore ConfigureKeyStore (KeyStore keyStore)
		{
			AssertSelf ();

			return keyStore;
		}
 public CryptoObjectHelper()
 {
     _keystore = KeyStore.GetInstance(KEYSTORE_NAME);
     _keystore.Load(null);
 }
예제 #45
0
파일: Tests.cs 프로젝트: flq/Raptile
        private static void insertthread(KeyStore<Guid> rap, List<Guid> guids, int start, int count, char c)
        {
            for (int i = 0; i < count; i++)
            {
                rap.Set(guids[i + start], "" + (i + start));

                if (i % 100000 == 0)
                {
                    Console.Write(c);
                }
            }
        }
예제 #46
0
파일: Tests.cs 프로젝트: flq/Raptile
 private static void readthread(KeyStore<Guid> rap, List<Guid> guids, int count, char c)
 {
     Thread.Sleep(5000);
     int notfound = 0;
     for (int i = 0; i < count; i++)
     {
         string bb;
         if (rap.Get(guids[i], out bb))
         {
             if (bb != "" + i)
                 notfound++;
         }
         else
             notfound++;
         if (i % 100000 == 0)
         {
             Console.Write(c);
         }
     }
     if (notfound > 0)
     {
         Console.WriteLine("not found = " + notfound);
         Assert.Fail();
     }
     Console.WriteLine("read done");
 }
예제 #47
0
 public SSLSocketFactoryEx(KeyStore truststore) : base(truststore)
 {
     ITrustManager tm = new X509TrustManager();
     sslContext.Init(null, new ITrustManager[] { tm }, null);
 }
예제 #48
0
파일: Tests.cs 프로젝트: flq/Raptile
 private static void threadtest(KeyStore<Guid> rap)
 {
     const int count = 1000000;
     var guids = new List<Guid>();
     Console.WriteLine("building list...");
     for (int i = 0; i < 2 * count; i++)
         guids.Add(Guid.NewGuid());
     Console.WriteLine("starting...");
     var t1 = new Thread(() => insertthread(rap, guids, 0, count, '.'));
     var t2 = new Thread(() => insertthread(rap, guids, count, count, '-'));
     var t3 = new Thread(() => readthread(rap, guids, count, 'R'));
     t3.Start();
     t2.Start();
     t1.Start();
     t3.Join();
     t2.Join();
     t1.Join();
 }
예제 #49
0
파일: Tests.cs 프로젝트: flq/Raptile
 public void StringKeyTest()
 {
     var db = new KeyStore<string>(_fileSystem, new Settings("strings1"));
     for (var i = 0; i < 100000; i++)
     {
         db.Set("asdfasd" + i, "" + i);
     }
     db.Dispose();
 }
예제 #50
0
 /**
  * This method is called when a key store needs to be loaded.
  * @remark The application must call <tt>KeyStore#PutKeys</tt> to put the new key store data into the
  * internal key store.
  *
  * @param store   Reference to the KeyStore to be loaded.
  *
  * @return
  *      - QStatus.OK if the load request was satisfied
  *      - An error status otherwise
  *
  */
 public abstract QStatus LoadRequest(KeyStore store);
예제 #51
0
 /**
  * This method is called when a key store needs to be stored.
  * @remark The application must call <tt>KeyStore#GetKeys</tt> to obtain the key data to be stored.
  *
  * @param store   Reference to the KeyStore to be stored.
  *
  * @return
  *      - QStatus.OK if the store request was satisfied
  *      - An error status otherwise
  */
 public abstract QStatus StoreRequest(KeyStore store);
		/// <summary>
		/// Create and configure an instance of <see cref="TrustManagerFactory"/>. The <paramref name="keyStore"/> parameter is set to the
		/// return value of the <see cref="ConfigureKeyStore"/> method, so it might be null if the application overrode the method and provided
		/// no key store. It will not be <c>null</c> when the default implementation is used. The application can return <c>null</c> from this 
		/// method in which case AndroidClientHandler will create its own instance of the trust manager factory provided that the <see cref="TrustCerts"/>
		/// list contains at least one valid certificate. If there are no valid certificates and this method returns <c>null</c>, no custom 
		/// trust manager will be created since that would make all the HTTPS requests fail.
		/// </summary>
		/// <returns>The trust manager factory.</returns>
		/// <param name="keyStore">Key store.</param>
		protected virtual TrustManagerFactory ConfigureTrustManagerFactory (KeyStore keyStore)
		{
			AssertSelf ();

			return null;
		}