/// <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); } }
void InitCipher() { try { mKeyStore.Load(null); var key = mKeyStore.GetKey(KEY_NAME, null); mCipher.Init(CipherMode.EncryptMode, key); } catch (KeyPermanentlyInvalidatedException e) { // This happens if the lock screen has been disabled or reset after the key was // generated, or if a fingerprint got enrolled after the key was generated. Toast.MakeText(this, "Keys are invalidated after created. Retry the purchase\n" + e.Message, ToastLength.Long).Show(); } catch (KeyStoreException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (CertificateException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (UnrecoverableKeyException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (IOException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (InvalidKeyException e) { throw new RuntimeException("Failed to init Cipher", e); } }
/// <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(); } }
protected override KeyStore ConfigureKeyStore(KeyStore keyStore) { if (_keyStore != null) { return(_keyStore); } _keyStore = KeyStore.GetInstance(KeyStore.DefaultType); _keyStore.Load(null, null); CertificateFactory cff = CertificateFactory.GetInstance("X.509"); foreach (var cer in _supported) { Java.Security.Cert.Certificate cert; // Add your Certificate to the Assets folder and address it here by its name using (var certStream = Android.App.Application.Context.Assets.Open(cer.Value)) { cert = cff.GenerateCertificate(certStream); } _keyStore.SetCertificateEntry(cer.Key, cert); } return(_keyStore); }
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); } }
public FingerprintService( FragmentActivity fragmentActivity, Context applicationContext, IObservable <Unit> applicationActivated, CoreDispatcher dispatcher, IScheduler backgroundScheduler, FuncAsync <BiometricPrompt.PromptInfo> promptInfoBuilder) { fragmentActivity.Validation().NotNull(nameof(fragmentActivity)); applicationActivated.Validation().NotNull(nameof(applicationActivated)); backgroundScheduler.Validation().NotNull(nameof(backgroundScheduler)); _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); _promptInfoBuilder = promptInfoBuilder ?? throw new ArgumentNullException(nameof(promptInfoBuilder)); var executor = ContextCompat.GetMainExecutor(applicationContext); var callback = new AuthenticationCallback(OnAuthenticationSucceeded, OnAuthenticationFailed, OnAuthenticationError); _BiometricPrompt = new BiometricPrompt(fragmentActivity, executor, callback); _BiometricManager = BiometricManager.From(Application.Context); _keyStore = KeyStore.GetInstance(ANDROID_KEYSTORE); _keyStore.Load(null); _canAuthenticate = applicationActivated .ObserveOn(backgroundScheduler) .StartWith(backgroundScheduler, Unit.Default) .Select(_ => _BiometricManager.CanAuthenticate()) .Replay(1, backgroundScheduler) .RefCount(); }
public static string DecodeBase64AndDecrypt( string alias, string cipherText) { byte[] full = Convert.FromBase64String(cipherText); byte[] iv = new byte[16]; byte[] cipherBytes = new byte[full.Length - 16]; Array.Copy(full, iv, iv.Length); Array.Copy(full, 16, cipherBytes, 0, cipherBytes.Length); KeyStore keyStore = KeyStore.GetInstance("AndroidKeyStore"); keyStore.Load(null); Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS7Padding"); IvParameterSpec spec = new IvParameterSpec(iv); ISecretKey key = GetSecretKey(keyStore, alias); if (key != null) { cipher.Init(CipherMode.DecryptMode, key, spec); byte[] plainTextBytes = cipher.DoFinal(cipherBytes); string plainText = System.Text.Encoding.UTF8.GetString(plainTextBytes); return(plainText); } else { return(String.Empty); } }
public PlatformEncryptionKeyHelper(Context context, string keyName) { _context = context; _keyName = keyName.ToLowerInvariant(); _androidKeyStore = KeyStore.GetInstance(KEYSTORE_NAME); _androidKeyStore.Load(null); }
public KeyStoreImpl(Context context, string keyStoreAlias) { appContext = context; alias = keyStoreAlias; keyStore = KeyStore.GetInstance(CONST_ANDROIDKEY); keyStore.Load(null); }
public Task <bool> ValidateIntegrityAsync() { if (Build.VERSION.SdkInt < BuildVersionCodes.M) { return(Task.FromResult(true)); } _keystore.Load(null); IKey key = _keystore.GetKey(KeyName, null); Cipher cipher = Cipher.GetInstance(Transformation); try { cipher.Init(CipherMode.EncryptMode, key); } catch (KeyPermanentlyInvalidatedException e) { // Biometric has changed return(Task.FromResult(false)); } catch (UnrecoverableKeyException e) { // Biometric was disabled and re-enabled return(Task.FromResult(false)); } catch (InvalidKeyException e) { // Fallback for old bitwarden users without a key CreateKey(); } return(Task.FromResult(true)); }
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; }
public CryptoObjectHelper(CipherMode cipherMode, byte[] iv) { _mode = cipherMode; _iv = iv; _keystore = KeyStore.GetInstance(KEYSTORE_NAME); _keystore.Load(null); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="GeneralSecurityException"/> internal X509TrustManager LoadTrustManager() { X509TrustManager trustManager = null; KeyStore ks = KeyStore.GetInstance(type); lastLoaded = file.LastModified(); FileInputStream @in = new FileInputStream(file); try { ks.Load(@in, password.ToCharArray()); Log.Debug("Loaded truststore '" + file + "'"); } finally { @in.Close(); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.GetInstance(SSLFactory .Sslcertificate); trustManagerFactory.Init(ks); TrustManager[] trustManagers = trustManagerFactory.GetTrustManagers(); foreach (TrustManager trustManager1 in trustManagers) { if (trustManager1 is X509TrustManager) { trustManager = (X509TrustManager)trustManager1; break; } } return(trustManager); }
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); } }
public AndroidAccountManagerPreM(Context context, string sharedPreferenceName) { _context = context; _sharedPreferenceName = sharedPreferenceName; _keyStore = KeyStore.GetInstance(AndroidKeyStore); _keyStore.Load(null); }
public KeyStoreStorageService(char[] password) { _keyStore = KeyStore.GetInstance(KeyStore.DefaultType); _protection = new KeyStore.PasswordProtection(password); if (File.FileExists(StorageFile)) { using (var stream = new IsolatedStorageFileStream(StorageFile, FileMode.Open, FileAccess.Read, File)) { _keyStore.Load(stream, password); } } else { _keyStore.Load(null, password); } }
/// <summary> /// Preinitialize fields /// </summary> public static void InitializeSecuritySystem() { _keyStore = KeyStore.GetInstance(STORE_NAME); _keyStore.Load(null); _notes_path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "notes.dat"); _tDES_key_path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "key.dat"); }
/// <exception cref="GeneralSecurityException"/> /// <exception cref="System.IO.IOException"/> private static KeyStore CreateEmptyKeyStore() { KeyStore ks = KeyStore.GetInstance("JKS"); ks.Load(null, null); // initialize return(ks); }
private void InitCipher(Cipher cipher, string storeKeyName) { try { keyStore.Load(null); IKey secretKey = keyStore.GetKey(storeKeyName, null); cipher.Init(CipherMode.EncryptMode, secretKey); } catch (Java.Lang.Exception e) { if (e is KeyStoreException | e is CertificateException | e is UnrecoverableKeyException | e is IOException | e is NoSuchAlgorithmException | e is InvalidKeyException) { throw new RuntimeException("Failed to init Cipher. " + e.Message, e); } } }
/// <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); } } } }
private async Task <KeyStore> GetOrCreateKeyStoreAsync(char[] password) { KeyStore keyStore = KeyStore.GetInstance("BKS"); try { using (Stream inputStream = await OpenKeyStoreFileForInputAsync().ConfigureAwait(false)) { keyStore.Load(inputStream, password); } } catch (Exception) { keyStore.Load(null); } return(keyStore); }
public KeyStoreCryptoService() { _keyStore = KeyStore.GetInstance("AndroidKeyStore"); _keyStore.Load(null); if (!_keyStore.ContainsAlias(_alias)) { CreateNewKey(_alias); } }
private void GenKey() { keyStore = KeyStore.GetInstance("AndroidKeyStore"); KeyGenerator keyGenerator = null; keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore"); keyStore.Load(null); keyGenerator.Init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt).SetBlockModes(KeyProperties.BlockModeCbc).SetUserAuthenticationRequired(true).SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7).Build()); keyGenerator.GenerateKey(); }
void SetupSSL(HttpsURLConnection httpsConnection) { if (httpsConnection == null) { return; } SSLSocketFactory socketFactory = ConfigureCustomSSLSocketFactory(httpsConnection); if (socketFactory != null) { httpsConnection.SSLSocketFactory = socketFactory; return; } KeyStore keyStore = KeyStore.GetInstance(KeyStore.DefaultType); keyStore.Load(null, null); bool gotCerts = TrustedCerts?.Count > 0; if (gotCerts) { for (int i = 0; i < TrustedCerts.Count; i++) { Certificate cert = TrustedCerts [i]; if (cert == null) { continue; } keyStore.SetCertificateEntry($"ca{i}", cert); } } keyStore = ConfigureKeyStore(keyStore); KeyManagerFactory kmf = ConfigureKeyManagerFactory(keyStore); TrustManagerFactory tmf = ConfigureTrustManagerFactory(keyStore); if (tmf == null) { // If there are no certs and no trust manager factory, we can't use a custom manager // because it will cause all the HTTPS requests to fail because of unverified trust // chain if (!gotCerts) { return; } tmf = TrustManagerFactory.GetInstance(TrustManagerFactory.DefaultAlgorithm); tmf.Init(keyStore); } SSLContext context = SSLContext.GetInstance("TLS"); context.Init(kmf?.GetKeyManagers(), tmf.GetTrustManagers(), null); httpsConnection.SSLSocketFactory = context.SocketFactory; }
private void _algoritmCriptare() { _creareCheie = KeyStore.GetInstance("AndroidKeyStore"); KeyGenerator _generator = null; _generator = KeyGenerator.GetInstance(_algoCheie, "AndroidKeyStore"); _creareCheie.Load(null); _generator.Init(new KeyGenParameterSpec.Builder(_cheie, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt) .SetBlockModes(_dependenta).SetUserAuthenticationRequired(true) .SetEncryptionPaddings(_umplere).Build()); _generator.GenerateKey(); }
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); GenerateStoreKey(); GenerateAesKey(); }
private string GetPrivateKey() { try { var keyStore = KeyStore.Load(_password, _appsetting.Keystore); return(keyStore.PrivateKey.ToString()); } catch (Exception e) { _logger.Error($"Marvin was unable to open the KeyStore, did you enter the correct password? \n {e}"); throw new Exception(e.ToString()); } }
public bool InitCipher() { try { mKeyStore.Load(null); var key = mKeyStore.GetKey(KEY_NAME, null); mCipher.Init(CipherMode.EncryptMode, key); return(true); } catch (KeyPermanentlyInvalidatedException) { return(false); } catch (KeyStoreException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (CertificateException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (UnrecoverableKeyException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (IOException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to init Cipher", e); } catch (InvalidKeyException e) { throw new RuntimeException("Failed to init Cipher", e); } }
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); } }
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 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 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); } }
public CryptoObjectHelper() { _keystore = KeyStore.GetInstance(KEYSTORE_NAME); _keystore.Load(null); }