Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyVaultStorage" /> class.
        /// </summary>
        public KeyVaultStorage()
        {
            try
            {
                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);
                }
            }
            catch (Exception ex)
            {
                var exceptionHandler = new ExceptionHandler(typeof(KeyVaultStorage).FullName + "._constructor", ex);
            }
        }
        /// <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);
            }

        }
Ejemplo n.º 3
0
        public void Init(string protectionPassword)
        {
            if (string.IsNullOrWhiteSpace(protectionPassword))
            {
                throw new ArgumentException("Cannot initialize without protection password.", nameof(protectionPassword));
            }

            _userSelectedPassword = protectionPassword.ToCharArray();

            _keyStore = KeyStore.GetInstance(KeyStore.DefaultType);

            _passwordProtection = new KeyStore.PasswordProtection(_userSelectedPassword);

            try
            {
                lock (_fileLock)
                {
                    using (var s = Context.OpenFileInput(FileName))
                    {
                        _keyStore.Load(s, _userSelectedPassword);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                LoadEmptyKeyStore(_userSelectedPassword);
            }

            _keychainInitialized = true;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// In Android we have to call this method first.
        /// This will make sure that the store will be initialized using a user provided key as password.
        /// </summary>
        /// <param name="password">The password for the KeyStore</param>
        /// <param name="fileName">A filename for the KeyStore</param>
        public void Initialize(string password, string fileName = "Excalibur.Store")
        {
            _password = password.ToCharArray();
            _fileName = fileName;

            if (_password == null)
            {
                throw new ArgumentNullException(nameof(_password), "Please call ProtectedStore.Init(<password>, <fileName?>) first.");
            }

            _context            = global::Android.App.Application.Context;
            _keyStore           = KeyStore.GetInstance(KeyStore.DefaultType);
            _passwordProtection = new KeyStore.PasswordProtection(_password);

            try
            {
                lock (FileLock)
                {
                    using (var stream = _context.OpenFileInput(_fileName))
                    {
                        _keyStore.Load(stream, _password);
                    }
                }
            }
            catch (Java.IO.FileNotFoundException)
            {
                _keyStore.Load(null, _password);
            }
            catch (Java.IO.IOException)
            {
                throw new ProtectedStoreException();
            }
        }
Ejemplo n.º 5
0
		static KeyStore LoadKeyStore(string clientId, string key)
		{
			var context = global::Android.App.Application.Context;
			KeyStore ks;
			if(keyStores.TryGetValue(clientId, out ks))
				return ks;
			var pw = key.ToCharArray();
			ks = KeyStore.GetInstance(KeyStore.DefaultType);

			var prot = new KeyStore.PasswordProtection(pw);

			try
			{
				lock(fileLock)
				{
					using(var s = context.OpenFileInput(clientId))
					{
						ks.Load(s, pw);
					}
				}
			}
			catch(FileNotFoundException)
			{
				//ks.Load (null, Password);
				LoadEmptyKeyStore(ks, pw);
			}
			keyStores[clientId] = ks;
			return ks;
		}
Ejemplo n.º 6
0
        private async Task <byte[]> GetEncryptionKeyLockedAsync(string keyName)
        {
            byte[] key = null;

            try
            {
                char[]   deviceId = GetDeviceId().ToCharArray();
                KeyStore keyStore = await GetOrCreateKeyStoreAsync(deviceId).ConfigureAwait(false);

                KeyStore.IProtectionParameter protectionParameter = new KeyStore.PasswordProtection(deviceId);
                KeyStore.SecretKeyEntry       secretKeyEntry      = (KeyStore.SecretKeyEntry)keyStore.GetEntry(keyName, protectionParameter);

                if (secretKeyEntry != null)
                {
                    ISecretKey secretKey = secretKeyEntry.SecretKey;
                    if (secretKey != null)
                    {
                        key = secretKey.GetEncoded();
                    }
                }
            }
            catch (FileNotFoundException)
            {
                // If the file isn't found, it's not a big deal and should mean it's just the first run.
                // The caller or the GetOrCreate method above will need to create it if we don't find it here.
            }

            return(key);
        }
Ejemplo n.º 7
0
        static Tuple <KeyStore, KeyStore.PasswordProtection> LoadKeyStore(Context context)
        {
            // Get our secure key which will be randomly created the first time the app is run
            var secureKey = GetSecureKey(context);
            var keyStore  = KeyStore.GetInstance(KeyStore.DefaultType);
            var prot      = new KeyStore.PasswordProtection(secureKey);

            try
            {
                lock (fileLock)
                {
                    if (context.GetFileStreamPath(FILENAME)?.Exists() ?? false)
                    {
                        using (var s = context.OpenFileInput(FILENAME))
                            keyStore.Load(s, secureKey);
                    }
                    else
                    {
                        keyStore.Load(null, secureKey);
                    }
                }
            }
            catch
            {
                keyStore.Load(null, secureKey);
            }

            return(Tuple.Create(keyStore, prot));
        }
Ejemplo n.º 8
0
        static KeyStore LoadKeyStore(string clientId, string key)
        {
            var      context = global::Android.App.Application.Context;
            KeyStore ks;

            if (keyStores.TryGetValue(clientId, out ks))
            {
                return(ks);
            }
            var pw = key.ToCharArray();

            ks = KeyStore.GetInstance(KeyStore.DefaultType);

            var prot = new KeyStore.PasswordProtection(pw);

            try
            {
                lock (fileLock)
                {
                    using (var s = context.OpenFileInput(clientId))
                    {
                        ks.Load(s, pw);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                //ks.Load (null, Password);
                LoadEmptyKeyStore(ks, pw);
            }
            keyStores[clientId] = ks;
            return(ks);
        }
     public 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);
         }
     }
Ejemplo n.º 10
0
        private static readonly char[] _password = "******".ToCharArray(); //todo: change this

        private void InitializeStore()
        {
            this._context = Android.App.Application.Context;
            _keyStore = KeyStore.GetInstance(KeyStore.DefaultType);
            _prot = new KeyStore.PasswordProtection(_password);

            try
            {
                lock (fileLock)
                {
                   if(!this.FileExists(_context, _fileName))
                    {
                        LoadEmptyKeyStore(_password);
                    }
                   else
                    {
                        using (var f = _context.OpenFileInput(_fileName))
                        {
                            _keyStore.Load(f, _password);
                        }
                    }
                }
            }
            catch (Exception ex) when (ex is Java.IO.FileNotFoundException || ex is System.IO.FileNotFoundException)
            {
                System.Diagnostics.Debug.WriteLine($"Caught {ex.GetType().ToString()} in Android.AuthService.InitializeStore.");
                LoadEmptyKeyStore(_password);
            }
        }
Ejemplo n.º 11
0
        /// <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);
            }
        }
Ejemplo n.º 12
0
        KeychainResult getItemFromKeychain(string service)
        {
            var context = Android.App.Application.Context;

            var password = service.ToCharArray();

            var protection = new KeyStore.PasswordProtection(password);

            var keystore = getKeystore(service);

            var aliases = keystore.Aliases();

            while (aliases.HasMoreElements)
            {
                var alias = aliases.NextElement().ToString();

                var item = keystore.GetEntry(alias, protection) as KeyStore.SecretKeyEntry;

                if (item != null)
                {
                    var bytes = item.SecretKey.GetEncoded();

                    var serialized = System.Text.Encoding.UTF8.GetString(bytes);

                    return(new KeychainResult(alias, serialized));
                }
            }

            return(new KeychainResult());
        }
Ejemplo n.º 13
0
        /// <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");
            }

            this._password = StoragePassword.ToCharArray();

            _keyStore   = KeyStore.GetInstance(KeyStore.DefaultType);
            _protection = new KeyStore.PasswordProtection(this._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);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Saves a {@code KeyStore.Entry} under the specified alias.
        /// The specified protection parameter is used to protect the
        /// {@code Entry}.
        ///
        /// <para> If an entry already exists for the specified alias,
        /// it is overridden.
        ///
        /// </para>
        /// </summary>
        /// <param name="alias"> save the {@code KeyStore.Entry} under this alias </param>
        /// <param name="entry"> the {@code Entry} to save </param>
        /// <param name="protParam"> the {@code ProtectionParameter}
        ///          used to protect the {@code Entry},
        ///          which may be {@code null}
        /// </param>
        /// <exception cref="KeyStoreException"> if this operation fails
        ///
        /// @since 1.5 </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException
        public virtual void EngineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam)
        {
            // get password
            if (protParam != null && !(protParam is KeyStore.PasswordProtection))
            {
                throw new KeyStoreException("unsupported protection parameter");
            }
            KeyStore.PasswordProtection pProtect = null;
            if (protParam != null)
            {
                pProtect = (KeyStore.PasswordProtection)protParam;
            }

            // set entry
            if (entry is KeyStore.TrustedCertificateEntry)
            {
                if (protParam != null && pProtect.Password != null)
                {
                    // pre-1.5 style setCertificateEntry did not allow password
                    throw new KeyStoreException("trusted certificate entries are not password-protected");
                }
                else
                {
                    KeyStore.TrustedCertificateEntry tce = (KeyStore.TrustedCertificateEntry)entry;
                    EngineSetCertificateEntry(alias, tce.TrustedCertificate);
                    return;
                }
            }
            else if (entry is KeyStore.PrivateKeyEntry)
            {
                if (pProtect == null || pProtect.Password == null)
                {
                    // pre-1.5 style setKeyEntry required password
                    throw new KeyStoreException("non-null password required to create PrivateKeyEntry");
                }
                else
                {
                    EngineSetKeyEntry(alias, ((KeyStore.PrivateKeyEntry)entry).PrivateKey, pProtect.Password, ((KeyStore.PrivateKeyEntry)entry).CertificateChain);
                    return;
                }
            }
            else if (entry is KeyStore.SecretKeyEntry)
            {
                if (pProtect == null || pProtect.Password == null)
                {
                    // pre-1.5 style setKeyEntry required password
                    throw new KeyStoreException("non-null password required to create SecretKeyEntry");
                }
                else
                {
                    EngineSetKeyEntry(alias, ((KeyStore.SecretKeyEntry)entry).SecretKey, pProtect.Password, (Certificate[])null);
                    return;
                }
            }

//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
            throw new KeyStoreException("unsupported entry type: " + entry.GetType().FullName);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Xamarin.Auth.AndroidAccountStore"/> class
        /// with a KeyStore password provided by the application.
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="password">KeyStore Password.</param>
        public AndroidAccountStore(Context context, string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            Password = password.ToCharArray();

            this.context = context;

            ks   = KeyStore.GetInstance(KeyStore.DefaultType);
            prot = new KeyStore.PasswordProtection(Password);

            try
            {
                lock (fileLock)
                {
                    if (!this.FileExists(context, FileName))
                    {
                        LoadEmptyKeyStore(Password);
                    }
                    else
                    {
                        using (var s = context.OpenFileInput(FileName))
                        {
                            ks.Load(s, Password);
                        }
                    }
                }
            }
            catch (FileNotFoundException)
            {
                LoadEmptyKeyStore(Password);
            }
            catch (Java.IO.IOException ex)
            {
                if (ex.Message == "KeyStore integrity check failed.")
                {
                    // Migration scenario: this exception means that the keystore could not be opened
                    // with the app provided password, so there is probably an existing keystore
                    // that was encoded with the old hard coded password, which was deprecated.
                    // We'll try to open the keystore with the old password, and migrate the contents
                    // to a new one that will be encoded with the new password.
                    //MigrateKeyStore(context);
                    try
                    {
                        //try with the original password
                        MigrateKeyStore(context, PasswordHardCodedOriginal);
                    }
                    catch (System.Exception)
                    {
                        //migrate using the default
                        MigrateKeyStore(context);
                    }
                }
            }
        }
Ejemplo n.º 16
0
		static internal void SetSecured(string key, string value, string clientId, string service, string sharedGrou = null)
		{
			var ks = LoadKeyStore(clientId, service);

			var entry = new KeyStore.SecretKeyEntry(new SecretAccount(value));
			var protect = new KeyStore.PasswordProtection(service.ToCharArray());
			ks.SetEntry("{0} - {1}".Fmt(clientId, key), entry, protect);
			Save(clientId, service, ks);
		}
Ejemplo n.º 17
0
 /// <inheritdoc />
 public void Terminate()
 {
     _keyStore           = null;
     _passwordProtection = null;
     lock (FileLock)
     {
         _context  = null;
         _password = null;
     }
 }
Ejemplo n.º 18
0
        static internal void SetSecured(string key, string value, string clientId, string service, string sharedGrou = null)
        {
            var ks = LoadKeyStore(clientId, service);

            var entry   = new KeyStore.SecretKeyEntry(new SecretAccount(value));
            var protect = new KeyStore.PasswordProtection(service.ToCharArray());

            ks.SetEntry("{0} - {1}".Fmt(clientId, key), entry, protect);
            Save(clientId, service, ks);
        }
Ejemplo n.º 19
0
        /// <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);
            }
        }
        /// <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);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Gets a {@code KeyStore.Entry} for the specified alias
        /// with the specified protection parameter.
        /// </summary>
        /// <param name="alias"> get the {@code KeyStore.Entry} for this alias </param>
        /// <param name="protParam"> the {@code ProtectionParameter}
        ///          used to protect the {@code Entry},
        ///          which may be {@code null}
        /// </param>
        /// <returns> the {@code KeyStore.Entry} for the specified alias,
        ///          or {@code null} if there is no such entry
        /// </returns>
        /// <exception cref="KeyStoreException"> if the operation failed </exception>
        /// <exception cref="NoSuchAlgorithmException"> if the algorithm for recovering the
        ///          entry cannot be found </exception>
        /// <exception cref="UnrecoverableEntryException"> if the specified
        ///          {@code protParam} were insufficient or invalid </exception>
        /// <exception cref="UnrecoverableKeyException"> if the entry is a
        ///          {@code PrivateKeyEntry} or {@code SecretKeyEntry}
        ///          and the specified {@code protParam} does not contain
        ///          the information needed to recover the key (e.g. wrong password)
        ///
        /// @since 1.5 </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException
        public virtual KeyStore.Entry EngineGetEntry(String alias, KeyStore.ProtectionParameter protParam)
        {
            if (!EngineContainsAlias(alias))
            {
                return(null);
            }

            if (protParam == null)
            {
                if (EngineIsCertificateEntry(alias))
                {
                    return(new KeyStore.TrustedCertificateEntry(EngineGetCertificate(alias)));
                }
                else
                {
                    throw new UnrecoverableKeyException("requested entry requires a password");
                }
            }

            if (protParam is KeyStore.PasswordProtection)
            {
                if (EngineIsCertificateEntry(alias))
                {
                    throw new UnsupportedOperationException("trusted certificate entries are not password-protected");
                }
                else if (EngineIsKeyEntry(alias))
                {
                    KeyStore.PasswordProtection pp = (KeyStore.PasswordProtection)protParam;
                    char[] password = pp.Password;

                    Key key = EngineGetKey(alias, password);
                    if (key is PrivateKey)
                    {
                        Certificate[] chain = EngineGetCertificateChain(alias);
                        return(new KeyStore.PrivateKeyEntry((PrivateKey)key, chain));
                    }
                    else if (key is SecretKey)
                    {
                        return(new KeyStore.SecretKeyEntry((SecretKey)key));
                    }
                }
            }

            throw new UnsupportedOperationException();
        }
Ejemplo n.º 22
0
        protected void CopyKeyStoreContents(char[] oldPassword)
        {
            var oldKeyStore   = KeyStore.GetInstance(KeyStore.DefaultType);
            var oldProtection = new KeyStore.PasswordProtection(oldPassword);

            using (var s = context.OpenFileInput(FileName + "Old"))
            {
                oldKeyStore.Load(s, oldPassword);
                // Copy all aliases to a new keystore, using a different password
                var aliases = oldKeyStore.Aliases();
                while (aliases.HasMoreElements)
                {
                    var alias = aliases.NextElement().ToString();
                    var e     = oldKeyStore.GetEntry(alias, oldProtection) as KeyStore.SecretKeyEntry;
                    ks.SetEntry(alias, e, prot);
                }
            }
            Save();
        }
Ejemplo n.º 23
0
        public override Task <bool> LoadAsync()
        {
            var secureKey = GetKeyFromPreferences(context);
            var keyStore  = LoadKeyStore(context, secureKey);
            var password  = new KeyStore.PasswordProtection(secureKey);

            var entry = keyStore.GetEntry(FILENAME, password) as KeyStore.SecretKeyEntry;

            if (entry != null)
            {
                var bytes = entry.SecretKey.GetEncoded();

                var json = System.Text.Encoding.UTF8.GetString(bytes);

                data = JsonToDictionary(json);
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 24
0
        public KeyChainHelper(Func <Context> context, string keyStoreFileProtectionPassword, string fileName, string serviceId)
        {
            if (string.IsNullOrEmpty(keyStoreFileProtectionPassword))
            {
                throw new ArgumentNullException("Filename cannot be null or empty string");
            }

            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("Filename cannot be null or empty string");
            }

            if (string.IsNullOrEmpty(serviceId))
            {
                throw new ArgumentNullException("ServiceId cannot be null or empty string");
            }

            _keyStoreFileProtectionPassword = keyStoreFileProtectionPassword;
            _fileName  = fileName;
            _serviceId = serviceId;
            _fileProtectionPasswordArray = _keyStoreFileProtectionPassword.ToCharArray();

            this.getContext     = context;
            _androidKeyStore    = KeyStore.GetInstance(KeyStore.DefaultType);
            _passwordProtection = new KeyStore.PasswordProtection(_fileProtectionPasswordArray);

            try
            {
                lock (_fileLock)
                {
                    using (var s = getContext().OpenFileInput(_fileName))
                    {
                        _androidKeyStore.Load(s, _fileProtectionPasswordArray);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                //ks.Load (null, Password);
                LoadEmptyKeyStore(_fileProtectionPasswordArray);
            }
        }
Ejemplo n.º 25
0
 private void CreateStore()
 {
     _context        = Android.App.Application.Context;
     _keyStore       = KeyStore.GetInstance(KeyStore.DefaultType);
     _passProtection = new KeyStore.PasswordProtection(_password);
     try
     {
         lock (_fileLock)
         {
             using (var s = _context.OpenFileInput(_fileName))
             {
                 _keyStore.Load(s, _password);
             }
         }
     }
     catch (Java.IO.FileNotFoundException)
     {
         LoadEmptyKeyStore(_password);
     }
 }
Ejemplo n.º 26
0
        private async Task StoreKeyAsync(string keyName, ISecretKey key)
        {
            char[]   deviceId = GetDeviceId().ToCharArray();
            KeyStore keyStore = await GetOrCreateKeyStoreAsync(deviceId).ConfigureAwait(false);

            KeyStore.IProtectionParameter protectionParameter = new KeyStore.PasswordProtection(deviceId);

            // Create the SecretKeyEntry wrapper around the SecretKey
            KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(key);

            // Store the SecretKeyEntry in the KeyStore
            keyStore.SetEntry(keyName, secretKeyEntry, protectionParameter);

            // Write the KeyStore to the app's directory with appropriate permissions
            // Note: we're using the same key to protect the KeyStore as we are to protect the entry inside it.
            using (Stream fileStream = await OpenKeyStoreFileForOutputAsync().ConfigureAwait(false))
            {
                keyStore.Store(fileStream, deviceId);
            }
        }
Ejemplo n.º 27
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);
			}
		}
        public DroidKeychain()
        {
            _keyStore           = KeyStore.GetInstance(KeyStore.DefaultType);
            _passwordProtection = new KeyStore.PasswordProtection(Password);

            try
            {
                lock (fileLock)
                {
                    using (var s = Context.OpenFileInput(FileName))
                    {
                        _keyStore.Load(s, Password);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                LoadEmptyKeyStore(Password);
            }
        }
Ejemplo n.º 29
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);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Xamarin.Auth.AndroidAccountStore"/> class
        /// with a KeyStore password provided by the application.
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="password">KeyStore Password.</param>
        public SafeStore(Context context, string password, string fileName = "Arc4u.Secure.Store")
        {
            if (String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("password");
            }
            Password = password.ToCharArray();

            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            FileName = fileName;

            this.context = context;

            ks   = KeyStore.GetInstance(KeyStore.DefaultType);
            prot = new KeyStore.PasswordProtection(Password);

            try
            {
                lock (fileLock)
                {
                    if (!this.FileExists(context, FileName))
                    {
                        LoadEmptyKeyStore(Password);
                    }
                    else
                    {
                        using (var s = context.OpenFileInput(FileName))
                        {
                            ks.Load(s, Password);
                        }
                    }
                }
            }
            catch (Java.IO.FileNotFoundException)
            {
                LoadEmptyKeyStore(Password);
            }
        }
Ejemplo n.º 31
0
        public bool UnlockSecureStorage(string password)
        {
            _password           = password.ToCharArray();
            _passwordProtection = new KeyStore.PasswordProtection(_password);
            _keyStore           = KeyStore.GetInstance(KeyStore.DefaultType);

            try
            {
                lock (_fileLocker)
                {
                    var ctx = Android.App.Application.Context;
                    if (!this.FileExists(ctx, FileName))
                    {
                        LoadEmptyKeyStore(password.ToCharArray());
                        System.Diagnostics.Debug.WriteLine("created " + FileName);
                    }
                    else
                    {
                        using (var s = ctx.OpenFileInput(FileName))
                        {
                            _keyStore.Load(s, password.ToCharArray());
                            System.Diagnostics.Debug.WriteLine("loaded " + FileName);
                        }
                    }

                    IsUnlocked = true;
                }
            }
            catch (FileNotFoundException)
            {
                LoadEmptyKeyStore(password.ToCharArray());
                IsUnlocked = true;
                Save();
            }
            catch (Java.IO.IOException)
            {
                IsUnlocked = false;
            }

            return(IsUnlocked);
        }
Ejemplo n.º 32
0
        public KeyChainUtils(Func <Context> context, string keyStoreFileProtectionPassword, string fileName, string serviceId)
        {
            if (String.IsNullOrEmpty(keyStoreFileProtectionPassword))
            {
                keyStoreFileProtectionPassword = String.Empty;
            }
            if (String.IsNullOrEmpty(fileName))
            {
                fileName = ".keystore";
            }
            if (String.IsNullOrEmpty(serviceId))
            {
                serviceId = "Advexp.Settings";
            }

            _keyStoreFileProtectionPassword = keyStoreFileProtectionPassword;
            _fileName  = fileName;
            _serviceId = serviceId;

            _fileProtectionPasswordArray = _keyStoreFileProtectionPassword.ToCharArray();

            this.getContext     = context;
            _androidKeyStore    = KeyStore.GetInstance(KeyStore.DefaultType);
            _passwordProtection = new KeyStore.PasswordProtection(_fileProtectionPasswordArray);

            try
            {
                lock (_fileLock)
                {
                    using (var s = getContext().OpenFileInput(_fileName))
                    {
                        _androidKeyStore.Load(s, _fileProtectionPasswordArray);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                //ks.Load (null, Password);
                LoadEmptyKeyStore(_fileProtectionPasswordArray);
            }
        }
Ejemplo n.º 33
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);
            }
        }
Ejemplo n.º 34
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);
            }
        }
Ejemplo n.º 35
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;
        }
Ejemplo n.º 36
0
		static internal string GetSecured(string key, string clientId, string service, string sharedGroup)
		{
			var keyId = $"{clientId} - {key}";
			var prot = new KeyStore.PasswordProtection(service.ToCharArray());
			var ks = LoadKeyStore(clientId, service);
			var aliases = ks.Aliases();
			while(aliases.HasMoreElements)
			{
				var alias = aliases.NextElement().ToString();
				if(alias == keyId)
				{
					var e = ks.GetEntry(alias, prot) as KeyStore.SecretKeyEntry;
					if(e != null)
					{
						var bytes = e.SecretKey.GetEncoded();
						var serialized = System.Text.Encoding.UTF8.GetString(bytes);
						return serialized;
					}
				}
			}

			return "";
		}
Ejemplo n.º 37
0
        public override Task <bool> SaveAsync()
        {
            var secureKey = GetKeyFromPreferences(context);
            var keyStore  = LoadKeyStore(context, secureKey);
            var password  = new KeyStore.PasswordProtection(secureKey);

            var secretValue = new SecretValue(System.Text.Encoding.UTF8.GetBytes(DictionaryToJson(data)));

            var secretKeyEntry = new KeyStore.SecretKeyEntry(secretValue);

            keyStore.SetEntry(FILENAME, secretKeyEntry, password);

            lock (fileLock)
            {
                using (var stream = context.OpenFileOutput(FILENAME, FileCreationMode.Private))
                {
                    keyStore.Store(stream, secureKey);
                    stream.Flush();
                    stream.Close();
                }
            }
            return(Task.FromResult(true));
        }