private static IKey GetKeyFromKeyStore() { var ks = KeyStore.GetInstance(KeyStoreName); ks.Load(null); return(ks.GetKey(KeyAlias, null)); }
/// <summary> /// Set certificates for the trusted Root Certificate Authorities (Android implementation) /// </summary> /// <param name="certificates">Certificates for the CAs to trust</param> public virtual void SetTrustedRoots(params byte[][] certificates) { if (certificates == null) { _trustMgrFactory = null; _x509TrustManager = null; return; } var keyStore = KeyStore.GetInstance(KeyStore.DefaultType); keyStore.Load(null); var certFactory = CertificateFactory.GetInstance("X.509"); foreach (var certificate in certificates) { var cert = (X509Certificate)certFactory.GenerateCertificate(new System.IO.MemoryStream(certificate)); keyStore.SetCertificateEntry(cert.SubjectDN.Name, cert); } _trustMgrFactory = TrustManagerFactory.GetInstance(TrustManagerFactory.DefaultAlgorithm); _trustMgrFactory.Init(keyStore); foreach (var trustManager in TrustManagers) { _x509TrustManager = trustManager.JavaCast <IX509TrustManager>(); if (_x509TrustManager != null) { break; } } }
public CryptoObjectHelper(CipherMode cipherMode, byte[] iv) { _mode = cipherMode; _iv = iv; _keystore = KeyStore.GetInstance(KEYSTORE_NAME); _keystore.Load(null); }
private void InitDefaultCipherObject() { try { keyStore = KeyStore.GetInstance("AndroidKeyStore"); } catch (KeyStoreException e) { throw new RuntimeException("Failed to get an instance of KeyStore(AndroidKeyStore). " + e.Message, e); } try { keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore"); } catch (Java.Lang.Exception e) { throw new RuntimeException("Failed to get an instance of KeyGenerator(AndroidKeyStore)." + e.Message, e); } CreateSecretKey(storeKey, true); try { defaultCipher = Cipher.GetInstance(KeyProperties.KeyAlgorithmAes + "/" + KeyProperties.BlockModeCbc + "/" + KeyProperties.EncryptionPaddingPkcs7); } catch (Java.Lang.Exception e) { throw new RuntimeException("Failed to get an instance of Cipher", e); } InitCipher(defaultCipher, storeKey); }
public IEnumerable <byte> Read(SecureStorageRequest request) { var key = GetKey(request); var prefs = Application.Context.GetSharedPreferences(ServiceName, FileCreationMode.Private); var saved = prefs.GetString(key, null); if (saved == null) { return(null); } var data = Convert.FromBase64String(saved); if (_HasKeyStore) { var iv = Convert.FromBase64String(prefs.GetString($"{key}_iv", null)); var keyStore = KeyStore.GetInstance("AndroidKeyStore"); keyStore.Load(null); var entry = (KeyStore.SecretKeyEntry)keyStore.GetEntry(Alias, null); var cipher = Cipher.GetInstance("AES/CBC/PKCS7Padding"); cipher.Init(CipherMode.DecryptMode, entry.SecretKey, new IvParameterSpec(iv)); data = cipher.DoFinal(data); } return(data); }
KeyStore LoadKeyStore(Context context, char[] secureKey) { var keyStore = KeyStore.GetInstance(KeyStore.DefaultType); try { lock (fileLock) { if (context.GetFileStreamPath(FILENAME)?.Exists() ?? false) { using (var s = context.OpenFileInput(FILENAME)) keyStore.Load(s, secureKey); //decrypt (probably) } else { keyStore.Load(null, secureKey); } } } catch { keyStore.Load(null, secureKey); } return(keyStore); }
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)); }
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 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 KeyStoreImpl(Context context, string keyStoreAlias) { appContext = context; alias = keyStoreAlias; keyStore = KeyStore.GetInstance(CONST_ANDROIDKEY); keyStore.Load(null); }
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(); }
/// <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); } }
/// <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); } }
private static IKey GetEncryptionKey() { const string AndroidKeyStoreProviderName = "AndroidKeyStore"; const string KeyAlias = "SecureStoragePluginKey"; IKey output = null; var store = KeyStore.GetInstance(AndroidKeyStoreProviderName); store.Load(null); if (store.ContainsAlias(KeyAlias)) { output = store.GetKey(KeyAlias, null); } else { var generator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, AndroidKeyStoreProviderName); generator.Init(new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt) .SetBlockModes(KeyProperties.BlockModeGcm).SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone) .SetRandomizedEncryptionRequired(false).Build()); output = generator.GenerateKey(); } return(output); }
public PlatformEncryptionKeyHelper(Context context, string keyName) { _context = context; _keyName = keyName.ToLowerInvariant(); _androidKeyStore = KeyStore.GetInstance(KEYSTORE_NAME); _androidKeyStore.Load(null); }
KeyStore getKeystore(string service) { var context = Android.App.Application.Context; var serviceId = $"{context.PackageName}.nomadcode.botframework-{service}"; if (keyStoresCache.TryGetValue(serviceId, out KeyStore keystore)) { return(keystore); } var password = service.ToCharArray(); keystore = KeyStore.GetInstance(KeyStore.DefaultType); // var protection = new KeyStore.PasswordProtection (password); try { // TODO: this isn't right, fix it using (var stream = context.OpenFileInput(serviceId)) { keystore.Load(stream, password); } } catch (FileNotFoundException) { keystore.Load(null, password); } keyStoresCache [serviceId] = keystore; return(keystore); }
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 void Write(SecureStorageRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request), "Cannot write a null storage request"); } if (request.Data == null) { Delete(request); return; } var data = request.Data.ToArray(); var iv = default(string); var keyStore = KeyStore.GetInstance("AndroidKeyStore"); keyStore.Load(null); var entry = (KeyStore.SecretKeyEntry)keyStore.GetEntry(Alias, null); var cipher = Cipher.GetInstance("AES/CBC/PKCS7Padding"); cipher.Init(CipherMode.EncryptMode, entry.SecretKey); iv = Convert.ToBase64String(cipher.GetIV()); data = cipher.DoFinal(data); var prefs = Application.Context.GetSharedPreferences(ServiceName, FileCreationMode.Private); var editor = prefs.Edit(); var key = GetKey(request); editor.PutString(key, Convert.ToBase64String(data)); editor.PutString($"{key}_iv", iv); editor.Commit(); }
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 void SetClientCertificate(ClientCertificate certificate) { if (certificate == null) { return; } byte[] bytes; try { bytes = Convert.FromBase64String(certificate.RawData); } catch (Exception ex) { throw new HttpRequestException(FailureMessages.InvalidRawData, ex); } var stream = new System.IO.MemoryStream(bytes); var keyStore = KeyStore.GetInstance("PKCS12"); keyStore.Load(stream, certificate.Passphrase.ToCharArray()); var kmf = KeyManagerFactory.GetInstance("X509"); kmf.Init(keyStore, certificate.Passphrase.ToCharArray()); KeyManagers = kmf.GetKeyManagers(); }
/// <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(); } }
/** * Tries to encrypt some data with the generated key in CreateKey which * only works if the user has just authenticated via device credentials. */ void TryEncrypt() { try { var keyStore = KeyStore.GetInstance("AndroidKeyStore"); keyStore.Load(null); IKey secretKey = keyStore.GetKey(KEY_NAME, null); var cipher = Cipher.GetInstance( KeyProperties.KeyAlgorithmAes + "/" + KeyProperties.BlockModeCbc + "/" + KeyProperties.EncryptionPaddingPkcs7); // Try encrypting something, it will only work if the user authenticated within // the last AUTHENTICATION_DURATION_SECONDS seconds. cipher.Init(CipherMode.EncryptMode, (IKey)secretKey); cipher.DoFinal(SECRET_BYTE_ARRAY); // If the user has recently authenticated, you will reach here. ShowAlreadyAuthenticated(); } catch (UserNotAuthenticatedException) { // User is not authenticated, let's authenticate with device credentials. ShowAuthenticationScreen(); } catch (KeyPermanentlyInvalidatedException e) { // This happens if the lock screen has been disabled or reset after the key was // generated after the key was generated. Toast.MakeText(this, "Keys are invalidated after created. Retry the purchase\n" + e.Message, ToastLength.Short).Show(); } catch (Exception e) { throw new SystemException("Exception", e); } }
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 byte[] GetBytes(string key) { byte[] result = null; if (sharedPreferences.Contains(key)) { var loadedText = sharedPreferences.GetString(key, ""); var loadedBytes = Convert.FromBase64String(loadedText); if (loadedBytes.Length <= IvLength) { throw new InvalidOperationException("Invalid read data."); } var iv = new byte[IvLength]; Array.Copy(loadedBytes, 0, iv, 0, iv.Length); var encryptedBytes = new byte[loadedBytes.Length - iv.Length]; Array.Copy(loadedBytes, iv.Length, encryptedBytes, 0, encryptedBytes.Length); var keyStore = KeyStore.GetInstance(KeyStoreType); keyStore.Load(null); var storeKey = keyStore.GetKey(Alias, null); if (storeKey == null) { throw new InvalidOperationException("Could not get the KeyStore key."); } var cipher = Cipher.GetInstance(CipherTransformation); cipher.Init(CipherMode.DecryptMode, storeKey, new GCMParameterSpec(GcmTagLength, iv)); result = cipher.DoFinal(encryptedBytes); } return(result); }
/// <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 AndroidAccountManagerPreM(Context context, string sharedPreferenceName) { _context = context; _sharedPreferenceName = sharedPreferenceName; _keyStore = KeyStore.GetInstance(AndroidKeyStore); _keyStore.Load(null); }
/// <exception cref="GeneralSecurityException"/> /// <exception cref="System.IO.IOException"/> private static KeyStore CreateEmptyKeyStore() { KeyStore ks = KeyStore.GetInstance("JKS"); ks.Load(null, null); // initialize return(ks); }
const int initializationVectorLen = 12; // Android supports an IV of 12 for AES/GCM internal AndroidKeyStore(Context context, string keystoreAlias) { appContext = context; alias = keystoreAlias; keyStore = KeyStore.GetInstance(androidKeyStore); keyStore.Load(null); }