/// <summary> /// Initialize cipher for Encryption and Decription /// </summary> /// <param name="secureKey"></param> protected void InitCiphers(string secureKey) { try { IvParameterSpec ivSpec = GetIv(); SecretKeySpec secretKey = GetSecretKey(secureKey); _writer.Init(Cipher.EncryptMode, secretKey, ivSpec); _reader.Init(Cipher.DecryptMode, secretKey, ivSpec); _keyWriter.Init(Cipher.EncryptMode, secretKey); } catch (UnsupportedEncodingException e) { throw new SharedPreferencesManagerException(e); } catch (NoSuchAlgorithmException e) { throw new SharedPreferencesManagerException(e); } catch (InvalidKeyException e) { throw new SharedPreferencesManagerException(e); } catch (InvalidAlgorithmParameterException e) { throw new SharedPreferencesManagerException(e); } }
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); } }
/// <summary> /// Función encargada de encriptar los datos del usuario /// </summary> /// <param name="password"></param> /// <returns></returns> public ArrayList encryptOutlook(string password) { string semilla = "0uTl@k"; string marcaTiempo = ""; ArrayList resultado = new ArrayList(); string encriptado = ""; try { // do // { byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; IvParameterSpec ivspec = new IvParameterSpec(iv); marcaTiempo = (new SimpleDateFormat("ddMMyyyyHHmmss")).format(new Date()); KeySpec clave = new PBEKeySpec(marcaTiempo.ToCharArray(), Encoding.Default.GetBytes(semilla), 65536, 256); SecretKey hash = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(clave); SecretKeySpec key = new SecretKeySpec(hash.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, ivspec); encriptado = Base64.getEncoder().encodeToString(cipher.doFinal(Encoding.UTF8.GetBytes(password))); resultado.add(encriptado); resultado.add(marcaTiempo); } catch (Exception e) { System.Console.WriteLine("Error en la encriptacion: " + e.ToString()); resultado = new ArrayList(); } return(resultado); }
/** * Initialize the crypt. */ public int init(byte [] keyBytesArg, byte [] iv) { byte [] keyBytes; if (isPadKey()) { keyBytes = padKey(keyBytesArg); } else { keyBytes = keyBytesArg; } _key = new SecretKeySpec(keyBytes, getAlgorithm(_algorithm)); if (iv == null) { _iv = null; } else if (_mode.equals("CBC") || _mode.equals("CFB") || _mode.equals("OFB")) { _iv = new IvParameterSpec(iv); } else { _iv = null; } return(0); }
public static String Encode3DSData(String apiSecretMerchant, String jsonObject) { // Initialization vector byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // AES Key from the API merchant key byte[] key = Encoding.UTF8.GetBytes(apiSecretMerchant.Substring(0, 16)); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); // What we should encrypt byte[] toEncrypt = Encoding.UTF8.GetBytes(jsonObject); // Encrypt AesManaged tdes = new AesManaged(); tdes.Key = key; tdes.Mode = CipherMode.CBC; tdes.Padding = PaddingMode.PKCS7; tdes.IV = iv; ICryptoTransform crypt = tdes.CreateEncryptor(); byte[] cipher = crypt.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length); var encryptedText = Convert.ToBase64String(cipher); // Convert to base64 return(encryptedText); }
// Public encrypting/decrypting methods (for CryptoEngine calls). public virtual sbyte[] encrypt(sbyte[] @in, Key keySpec, sbyte[] iv) { IvParameterSpec ivec = new IvParameterSpec(iv); sbyte[] result = null; try { Cipher c = cipher; c.init(Cipher.ENCRYPT_MODE, keySpec, ivec); result = c.doFinal(@in); } catch (InvalidKeyException e) { Console.WriteLine("encrypt", e); } catch (InvalidAlgorithmParameterException e) { Console.WriteLine("encrypt", e); } catch (IllegalBlockSizeException e) { Console.WriteLine("encrypt", e); } catch (BadPaddingException e) { Console.WriteLine("encrypt", e); } return(result); }
protected internal static Cipher InitCipherForBlock(Cipher existing, int block, bool lastChunk, IEncryptionInfoBuilder builder, ISecretKey skey, int encryptionMode) { EncryptionHeader header = builder.GetHeader(); if (existing == null || lastChunk) { String pAdding = (lastChunk ? "PKCS5PAdding" : "NoPAdding"); existing = CryptoFunctions.GetCipher(skey, header.CipherAlgorithm, header.ChainingMode, header.KeySalt, encryptionMode, pAdding); } byte[] blockKey = new byte[4]; LittleEndian.PutInt(blockKey, 0, block); byte[] iv = CryptoFunctions.GenerateIv(header.HashAlgorithm, header.KeySalt, blockKey, header.BlockSize); AlgorithmParameterSpec aps; if (header.CipherAlgorithm == CipherAlgorithm.rc2) { aps = new RC2ParameterSpec(skey.GetEncoded().Length * 8, iv); } else { aps = new IvParameterSpec(iv); } existing.Init(encryptionMode, skey, aps); return(existing); }
public string DecriptFile(string filename, string name) { Java.IO.File extStore = Android.OS.Environment.GetExternalStoragePublicDirectory("Temp"); Android.Util.Log.Error("Decryption Started", extStore + ""); FileInputStream fis = new FileInputStream(extStore + "/" + filename); // createFile(filename, extStore); FileOutputStream fos = new FileOutputStream(extStore + "/" + "decrypted" + filename, false); System.IO.FileStream fs = System.IO.File.OpenWrite(extStore + "/" + name); Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(CipherMode.DecryptMode, skeySpec, iv); CipherOutputStream cos = new CipherOutputStream(fs, cipher); int b; byte[] d = new byte[1024 * 1024]; while ((b = fis.Read(d)) != -1) { cos.Write(d, 0, b); } System.IO.File.Delete(extStore + "/" + "decrypted" + filename); Android.Util.Log.Error("Decryption Ended", extStore + "/" + "decrypted" + name); return(extStore.ToString()); //return d; }
public void SaveFile(string name, Stream data) { string documentsPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "Temp"); Directory.CreateDirectory(documentsPath); string filePath = Path.Combine(documentsPath, name); // Length is 16 byte Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(CipherMode.EncryptMode, skeySpec, iv); // Wrap the output stream CipherInputStream cis = new CipherInputStream(data, cipher); byte[] bArray = new byte[1024 * 1024]; int b; using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate)) { while ((b = cis.Read(bArray)) != -1) { fs.Write(bArray, 0, b); } } }
public void decrypt() { try { string path = "/storage/emulated/0/jukebox/Songs"; // Log.d("Files", "Path: " + path); Java.IO.File directory = new Java.IO.File(path); Java.IO.File[] files = directory.ListFiles(); // Log.d("Files", "Size: " + files.length); for (int i = 0; i < files.Length; i++) { // Log.d("Files", "FileName:" + files[i].getName()); var fileName = files[i].Name; int index = fileName.LastIndexOf("."); if (index > 0) { fileName = fileName.Substring(0, index); } //Java.IO.File extStore = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies); Android.Util.Log.Error("Decryption Started", directory + ""); FileInputStream fis = new FileInputStream(directory + "/" + fileName + ".aes"); createFile(files[i].Name, directory); FileOutputStream fos = new FileOutputStream(directory + "/" + "decrypted" + fileName, false); System.IO.FileStream fs = System.IO.File.OpenWrite(directory + "/" + "decrypted" + fileName); // Create cipher Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(Javax.Crypto.CipherMode.DecryptMode, skeySpec, iv); startTime = System.DateTime.Now.Millisecond; CipherOutputStream cos = new CipherOutputStream(fs, cipher); int b; byte[] d = new byte[1024 * 1024]; while ((b = fis.Read(d)) != -1) { cos.Write(d, 0, b); } stopTime = System.DateTime.Now.Millisecond; Android.Util.Log.Error("Decryption Ended", directory + "/" + "decrypted" + fileName); Android.Util.Log.Error("Time Elapsed", ((stopTime - startTime) / 1000.0) + ""); cos.Flush(); cos.Close(); fis.Close(); } } catch (Exception e) { Android.Util.Log.Error("lv", e.Message); } }
/// <inheritdoc /> protected override Stream Decrypt(Stream inputStream) { var cipher = Cipher.GetInstance(_fullTransform); var iv = new IvParameterSpec(_iv, 0, cipher.BlockSize); cipher.Init(CipherMode.DecryptMode, _key, iv); return(new InputStreamInvoker(new CipherInputStream(inputStream, cipher))); }
/// <inheritdoc /> protected override Stream Encrypt(Stream outputStream) { var cipher = Cipher.GetInstance(_fullTransform); var iv = new IvParameterSpec(_iv, 0, cipher.BlockSize); cipher.Init(CipherMode.EncryptMode, _key, iv); return(new CipherStreamAdapter(new CipherOutputStream(outputStream, cipher))); }
public static byte[] encode(byte[] fileData) { byte[] data = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.Length, KEY_SPEC_ALGORITHM); Cipher cipher = Cipher.GetInstance(CIPHER_ALGORITHM, PROVIDER); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter)); cipher.Init(Javax.Crypto.CipherMode.EncryptMode, skeySpec, iv); return(cipher.DoFinal(fileData)); }
/// <summary> /// Requests that the specified Purchasable be purchased on behalf of the current user. /// The IAP client service is responsible for identifying the user and requesting credentials as appropriate, /// as well as providing all of the UI for the purchase flow. When purchases are successful, a Product object /// is returned that describes the product that was purchased. /// </summary> /// <param name="product">The Purchasable object that describes the item to be purchased.</param> /// <returns>Returns true if the purchase was successful.</returns> public async Task <bool> RequestPurchaseAsync(Product product) { if (ReferenceEquals(product, null)) { throw new ArgumentNullException("product"); } var tcs = new TaskCompletionSource <bool>(); // Create the Purchasable object from the supplied product var sr = SecureRandom.GetInstance("SHA1PRNG"); // This is an ID that allows you to associate a successful purchase with // it's original request. The server does nothing with this string except // pass it back to you, so it only needs to be unique within this instance // of your app to allow you to pair responses with requests. var uniqueId = sr.NextLong().ToString("X"); JSONObject purchaseRequest = new JSONObject(); purchaseRequest.Put("uuid", uniqueId); purchaseRequest.Put("identifier", product.Identifier); var purchaseRequestJson = purchaseRequest.ToString(); byte[] keyBytes = new byte[16]; sr.NextBytes(keyBytes); var key = new SecretKeySpec(keyBytes, "AES"); byte[] ivBytes = new byte[16]; sr.NextBytes(ivBytes); var iv = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding", "BC"); cipher.Init(CipherMode.EncryptMode, key, iv); var payload = cipher.DoFinal(Encoding.UTF8.GetBytes(purchaseRequestJson)); cipher = Cipher.GetInstance("RSA/ECB/PKCS1Padding", "BC"); cipher.Init(CipherMode.EncryptMode, _publicKey); var encryptedKey = cipher.DoFinal(keyBytes); var purchasable = new Purchasable( product.Identifier, Convert.ToBase64String(encryptedKey, Base64FormattingOptions.None), Convert.ToBase64String(ivBytes, Base64FormattingOptions.None), Convert.ToBase64String(payload, Base64FormattingOptions.None)); var listener = new PurchaseListener(tcs, _publicKey, product, uniqueId); RequestPurchase(purchasable, listener); // No timeout for purchase as it shows a user dialog return(await tcs.Task); }
public void encrypt(string filename, string path) { // Here you read the cleartext. try { var extStore = new Java.IO.File("/storage/emulated/0/jukebox/Songs"); startTime = System.DateTime.Now.Millisecond; Android.Util.Log.Error("Encryption Started", extStore + "/" + filename); // This stream write the encrypted text. This stream will be wrapped by // another stream. createFile(filename, extStore); var webRequest = WebRequest.Create(path); using (var response = webRequest.GetResponse()) using (var content = response.GetResponseStream()) using (var reader = new StreamReader(content)) { var strContent = reader.ReadToEnd(); // System.IO.FileStream fs = System.IO.File.OpenWrite(path); FileOutputStream fos = new FileOutputStream(extStore + "/" + filename + ".aes", false); // Length is 16 byte Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(Javax.Crypto.CipherMode.EncryptMode, skeySpec, iv); // Wrap the output stream CipherInputStream cis = new CipherInputStream(content, cipher); // Write bytes int b; byte[] d = new byte[1024 * 1024]; while ((b = cis.Read(d)) != -1) { fos.Write(d, 0, b); } // Flush and close streams. fos.Flush(); fos.Close(); cis.Close(); stopTime = System.DateTime.Now.Millisecond; Android.Util.Log.Error("Encryption Ended", extStore + "/5mbtest/" + filename + ".aes"); Android.Util.Log.Error("Time Elapsed", ((stopTime - startTime) / 1000.0) + ""); } } catch (Exception e) { Android.Util.Log.Error("lv", e.Message); } }
public void decrypt(string filename) { try { Java.IO.File extStore = new Java.IO.File("/storage/emulated/0/jukebox/Songs"); Android.Util.Log.Error("Decryption Started", extStore + ""); FileInputStream fis = new FileInputStream(extStore + "/" + filename + ".aes"); createFile(filename, extStore); FileOutputStream fos = new FileOutputStream(extStore + "/" + "decrypted" + filename, false); System.IO.FileStream fs = System.IO.File.OpenWrite(extStore + "/" + "decrypted" + filename); // Create cipher Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(Javax.Crypto.CipherMode.DecryptMode, skeySpec, iv); startTime = System.DateTime.Now.Millisecond; CipherOutputStream cos = new CipherOutputStream(fs, cipher); Java.IO.File file = new Java.IO.File("/storage/emulated/0/jukebox/Songs" + "/" + filename); if (file.Delete()) { Android.Util.Log.Error("File Deteted", extStore + filename); } else { Android.Util.Log.Error("File Doesn't exists", extStore + filename); } int b; byte[] d = new byte[1024 * 1024]; while ((b = fis.Read(d)) != -1) { cos.Write(d, 0, b); } stopTime = System.DateTime.Now.Millisecond; Android.Util.Log.Error("Decryption Ended", extStore + "/" + "decrypted" + filename); Android.Util.Log.Error("Time Elapsed", ((stopTime - startTime) / 1000.0) + ""); cos.Flush(); cos.Close(); fis.Close(); } catch (Exception e) { Android.Util.Log.Error("lv", e.Message); } }
public static byte[] decode(byte[] fileData) { byte[] decrypted; Cipher cipher = Cipher.GetInstance(CIPHER_ALGORITHM, PROVIDER); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(Javax.Crypto.CipherMode.DecryptMode, skeySpec, iv); decrypted = cipher.DoFinal(fileData); return(decrypted); }
public override bool Init() { Kp2aLog.Log("FP: Init for Dec"); try { _keystore.Load(null); var key = _keystore.GetKey(GetAlias(_keyId), null); var ivParams = new IvParameterSpec(_iv); _cipher.Init(CipherMode.DecryptMode, key, ivParams); _cryptoObject = new BiometricPrompt.CryptoObject(_cipher); return(true); } catch (KeyPermanentlyInvalidatedException e) { Kp2aLog.Log("FP: KeyPermanentlyInvalidatedException." + e.ToString()); return(false); } catch (KeyStoreException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (CertificateException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (IOException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (InvalidKeyException e) { throw new RuntimeException(FailedToInitCipher, e); } }
public virtual sbyte[] decrypt(sbyte[] @in, sbyte[] decKey, sbyte[] iv) { Key keySpec = new SecretKeySpec(decKey, "AES"); IvParameterSpec ivec = new IvParameterSpec(iv); sbyte[] result = null; try { Cipher c = cipher; c.init(Cipher.DECRYPT_MODE, keySpec, ivec); result = c.doFinal(@in); } catch (Exception e) { Console.WriteLine("decrypt", e); } return(result); }
protected byte[] Decrypt(byte[] key, byte[] iv, byte[] encrypted) { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); byte[] decrypted; try { Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec); decrypted = cipher.doFinal(encrypted); } catch (Exception e) { throw new EncryptionException("Could not decrypt Medtronic Message"); } return(decrypted); }
public override bool InitCipher() { try { _keystore.Load(null); var key = _keystore.GetKey(GetAlias(_keyId), null); var ivParams = new IvParameterSpec(_iv); _cipher.Init(CipherMode.DecryptMode, key, ivParams); _cryptoObject = new FingerprintManager.CryptoObject(_cipher); return(true); } catch (KeyPermanentlyInvalidatedException) { return(false); } catch (KeyStoreException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (CertificateException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (IOException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(FailedToInitCipher, e); } catch (InvalidKeyException e) { throw new RuntimeException(FailedToInitCipher, e); } }
internal DesEncrypter(SecretKey paramSecretKey) { sbyte[] arrayOfByte = new sbyte[] { -114, 18, 57, -100, 7, 114, 111, 90 }; IvParameterSpec ivParameterSpec = new IvParameterSpec(arrayOfByte); try { this.dcipher = (this.ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding")).getInstance("DES/CBC/PKCS5Padding"); this.ecipher.init(1, paramSecretKey, ivParameterSpec); this.dcipher.init(2, paramSecretKey, ivParameterSpec); } catch (InvalidAlgorithmParameterException) { } catch (NoSuchPaddingException) { } catch (NoSuchAlgorithmException) { } catch (InvalidKeyException) { } }
public override bool Init() { Kp2aLog.Log("FP: Init for Dec"); try { _keystore.Load(null); var aliases = _keystore.Aliases(); if (aliases == null) { Kp2aLog.Log("KS: no aliases"); } else { while (aliases.HasMoreElements) { var o = aliases.NextElement(); Kp2aLog.Log("alias: " + o?.ToString()); } Kp2aLog.Log("KS: end aliases"); } var key = _keystore.GetKey(GetAlias(_keyId), null); if (key == null) { throw new Exception("Failed to init cipher for fingerprint Init: key is null"); } var ivParams = new IvParameterSpec(_iv); _cipher.Init(CipherMode.DecryptMode, key, ivParams); _cryptoObject = new BiometricPrompt.CryptoObject(_cipher); return(true); } catch (KeyPermanentlyInvalidatedException e) { Kp2aLog.Log("FP: KeyPermanentlyInvalidatedException." + e.ToString()); return(false); } catch (KeyStoreException e) { throw new RuntimeException(FailedToInitCipher + " (keystore)", e); } catch (CertificateException e) { throw new RuntimeException(FailedToInitCipher + " (CertificateException)", e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(FailedToInitCipher + " (UnrecoverableKeyException)", e); } catch (IOException e) { throw new RuntimeException(FailedToInitCipher + " (IOException)", e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(FailedToInitCipher + " (NoSuchAlgorithmException)", e); } catch (InvalidKeyException e) { throw new RuntimeException(FailedToInitCipher + " (InvalidKeyException)" + e.ToString(), e); } }