Example #1
0
        public async Task <string> ReadAsync(string key)
        {
            try
            {
                using (await LockAndInitialize(key).ConfigureAwait(false))
                {
                    // read file
                    string file         = GetFilePath(key);
                    byte[] fileContents = File.ReadAllBytes(file);

                    // decrypt the file
                    SecretKeySpec keySpec = new SecretKeySpec(_encryptionKey, s_encryptionFlavor);
                    Cipher        cipher  = Cipher.GetInstance(s_encryptionFlavor);
                    cipher.Init(CipherMode.DecryptMode, keySpec);
                    byte[] decrypted = cipher.DoFinal(fileContents);

                    return(Encoding.UTF8.GetString(decrypted));
                }
            }
            catch (FileNotFoundException)
            {
                return(null);
            }
            catch (Exception e) when(!(e is IOException))
            {
                throw new IOException(string.Format(ClientResources.FileAccessErrorMessage, ClientResources.FileAccessActionRead, key), e);
            }
        }
Example #2
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);
        }
Example #3
0
        protected internal static Cipher InitCipherForBlock(Cipher cipher, int block,
                                                            IEncryptionInfoBuilder builder, ISecretKey skey, int encryptMode)
        {
            EncryptionVerifier ver      = builder.GetVerifier();
            HashAlgorithm      hashAlgo = ver.HashAlgorithm;

            byte[] blockKey = new byte[4];
            LittleEndian.PutUInt(blockKey, 0, block);
            MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo);

            hashAlg.Update(skey.GetEncoded());
            byte[]           encKey = hashAlg.Digest(blockKey);
            EncryptionHeader header = builder.GetHeader();
            int keyBits             = header.KeySize;

            encKey = CryptoFunctions.GetBlock0(encKey, keyBits / 8);
            if (keyBits == 40)
            {
                encKey = CryptoFunctions.GetBlock0(encKey, 16);
            }
            ISecretKey key = new SecretKeySpec(encKey, skey.GetAlgorithm());

            if (cipher == null)
            {
                cipher = CryptoFunctions.GetCipher(key, header.CipherAlgorithm, null, null, encryptMode);
            }
            else
            {
                cipher.Init(encryptMode, key);
            }
            return(cipher);
        }
        /// <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);
            }
        }
Example #5
0
        protected internal static byte[] hashInput(IEncryptionInfoBuilder builder, byte[] pwHash, byte[] blockKey, byte[] inputKey, int cipherMode)
        {
            EncryptionVerifier ver  = builder.GetVerifier();
            AgileDecryptor     dec  = (AgileDecryptor)builder.GetDecryptor();
            int           keySize   = dec.GetKeySizeInBytes();
            int           blockSize = dec.GetBlockSizeInBytes();
            HashAlgorithm hashAlgo  = ver.HashAlgorithm;

            byte[] salt = ver.Salt;

            byte[]     intermedKey = CryptoFunctions.GenerateKey(pwHash, hashAlgo, blockKey, keySize);
            ISecretKey skey        = new SecretKeySpec(intermedKey, ver.CipherAlgorithm.jceId);

            byte[] iv     = CryptoFunctions.GenerateIv(hashAlgo, salt, null, blockSize);
            Cipher cipher = CryptoFunctions.GetCipher(skey, ver.CipherAlgorithm, ver.ChainingMode, iv, cipherMode);

            byte[] hashFinal;

            try {
                inputKey  = CryptoFunctions.GetBlock0(inputKey, GetNextBlockSize(inputKey.Length, blockSize));
                hashFinal = cipher.DoFinal(inputKey);
                return(hashFinal);
            } catch (Exception e) {
                throw new EncryptedDocumentException(e);
            }
        }
Example #6
0
        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);
                }
            }
        }
 /// <exception cref="System.IO.IOException"/>
 public override KeyProvider.KeyVersion GetKeyVersion(string versionName)
 {
     readLock.Lock();
     try
     {
         SecretKeySpec key = null;
         try
         {
             if (!keyStore.ContainsAlias(versionName))
             {
                 return(null);
             }
             key = (SecretKeySpec)keyStore.GetKey(versionName, password);
         }
         catch (KeyStoreException e)
         {
             throw new IOException("Can't get key " + versionName + " from " + path, e);
         }
         catch (NoSuchAlgorithmException e)
         {
             throw new IOException("Can't get algorithm for key " + key + " from " + path, e);
         }
         catch (UnrecoverableKeyException e)
         {
             throw new IOException("Can't recover key " + key + " from " + path, e);
         }
         return(new KeyProvider.KeyVersion(GetBaseName(versionName), versionName, key.GetEncoded
                                               ()));
     }
     finally
     {
         readLock.Unlock();
     }
 }
        /// <exception cref="System.Exception"></exception>
        public override void Init(int mode, byte[] key, byte[] iv)
        {
            string pad = "NoPadding";

            //  if(padding) pad="PKCS5Padding";
            byte[] tmp;
            if (iv.Length > ivsize)
            {
                tmp = new byte[ivsize];
                System.Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (key.Length > bsize)
            {
                tmp = new byte[bsize];
                System.Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }
            try
            {
                SecretKeySpec skeySpec = new SecretKeySpec(key, "Blowfish");
                cipher = Sharpen.Cipher.GetInstance("Blowfish/CBC/" + pad);
                cipher.Init((mode == ENCRYPT_MODE ? Sharpen.Cipher.ENCRYPT_MODE : Sharpen.Cipher.
                             DECRYPT_MODE), skeySpec, new IvParameterSpec(iv));
            }
            catch (Exception e)
            {
                throw;
            }
        }
Example #9
0
    public Mac(SecretKeySpec key, string data)
    {
        switch (key.Method)
        {
        case EncryptionMethods.HMACMD5:
            mac = new HMACMD5(key.SecretKey);
            break;

        case EncryptionMethods.HMACSHA512:
            mac = new HMACSHA512(key.SecretKey);
            break;

        case EncryptionMethods.HMACSHA384:
            mac = new HMACSHA384(key.SecretKey);
            break;

        case EncryptionMethods.HMACSHA256:
            mac = new HMACSHA256(key.SecretKey);
            break;

        case EncryptionMethods.HMACSHA1:
            mac = new HMACSHA1(key.SecretKey);
            break;

        default:
            throw new NotSupportedException("not supported HMAC");
        }
        rawHmac = mac.ComputeHash(Cardinity.ENCODING.GetBytes(data));
    }
 /// <exception cref="System.Exception"></exception>
 public override void Init(int mode, byte[] key, byte[] iv)
 {
     byte[] tmp;
     if (key.Length > bsize)
     {
         tmp = new byte[bsize];
         System.Array.Copy(key, 0, tmp, 0, tmp.Length);
         key = tmp;
     }
     try
     {
         cipher = Sharpen.Cipher.GetInstance("RC4");
         SecretKeySpec _key = new SecretKeySpec(key, "RC4");
         cipher.Init((mode == ENCRYPT_MODE ? Sharpen.Cipher.ENCRYPT_MODE : Sharpen.Cipher.
                      DECRYPT_MODE), _key);
         byte[] foo = new byte[1];
         for (int i = 0; i < skip; i++)
         {
             cipher.Update(foo, 0, 1, foo, 0);
         }
     }
     catch (Exception e)
     {
         cipher = null;
         throw;
     }
 }
Example #11
0
        /// <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);
        }
        /// <inheritdoc />
        public CryptographicHash CreateHash(byte[] keyMaterial)
        {
            Requires.NotNull(keyMaterial, nameof(keyMaterial));

            var hash = GetAlgorithm(this.Algorithm);

#if __ANDROID__
#pragma warning disable CA2000 // Dispose objects before losing scope
            SecretKeySpec key = GetSecretKey(this.Algorithm, keyMaterial);
#pragma warning restore CA2000 // Dispose objects before losing scope
            try
            {
                hash.Init(key);
                return(new JavaCryptographicHashMac(hash));
            }
            catch
            {
                key.Dispose();
                throw;
            }
#else
            hash.Key = keyMaterial;
            return(new NetFxCryptographicHash(hash));
#endif
        }
Example #13
0
        protected internal static ISecretKey GenerateSecretKey(String password,
                                                               EncryptionVerifier ver)
        {
            if (password.Length > 255)
            {
                password = password.Substring(0, 255);
            }
            HashAlgorithm hashAlgo = ver.HashAlgorithm;
            MessageDigest hashAlg  = CryptoFunctions.GetMessageDigest(hashAlgo);

            byte[] hash = hashAlg.Digest(StringUtil.GetToUnicodeLE(password));
            byte[] salt = ver.Salt;
            hashAlg.Reset();
            for (int i = 0; i < 16; i++)
            {
                hashAlg.Update(hash, 0, 5);
                hashAlg.Update(salt);
            }

            hash = new byte[5];
            Array.Copy(hashAlg.Digest(), 0, hash, 0, 5);
            ISecretKey skey = new SecretKeySpec(hash, ver.CipherAlgorithm.jceId);

            return(skey);
        }
Example #14
0
        /// <summary>
        /// Returns the secret key to use for initializing the Mac.
        /// </summary>
        /// <param name="algorithm">The algorithm.</param>
        /// <param name="keyMaterial">The key material.</param>
        /// <returns>The secret key.</returns>
        internal static SecretKeySpec GetSecretKey(MacAlgorithm algorithm, byte[] keyMaterial)
        {
            string algorithmName = MacAlgorithmProviderFactory.GetAlgorithmName(algorithm);
            var    signingKey    = new SecretKeySpec(keyMaterial, algorithmName);

            return(signingKey);
        }
Example #15
0
        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;
        }
Example #16
0
        private IKey GetKey()
        {
            // Reform key object
            var jsonKey = _storageHelper.GetItem <byte[]>(_keyAlias);
            var key     = new SecretKeySpec(jsonKey, 0, jsonKey.Length, TRANSFORMATION);

            return(key);
        }
Example #17
0
        private ZipEntrySource fileToSource(FileInfo tmpFile, CipherAlgorithm cipherAlgorithm, byte[] keyBytes, byte[] ivBytes)
        {
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId);
            Cipher        ciDec    = CryptoFunctions.GetCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.DECRYPT_MODE, "PKCS5PAdding");
            ZipFile       zf       = new ZipFile(tmpFile.FullName);

            return(new AesZipFileZipEntrySource(zf, ciDec));
        }
Example #18
0
        // Normally should be private, may need to be public for our purposes
        public IKey GetKey()
        {
            // Pull key and reform it into a key
            var jsonKey = _storageHelper.GetItem <byte[]>(_keyAlias);
            var key     = new SecretKeySpec(jsonKey, 0, jsonKey.Length, TRANSFORMATION);

            return(key);
        }
        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);
            }
        }
Example #20
0
        /**
         * instead of a password, it's also possible to decrypt via certificate.
         * Warning: this code is experimental and hasn't been validated
         *
         * @see <a href="http://social.msdn.microsoft.com/Forums/en-US/cc9092bb-0c82-4b5b-ae21-abf643bdb37c/agile-encryption-with-certificates">Agile encryption with certificates</a>
         *
         * @param keyPair
         * @param x509
         * @return true, when the data can be successfully decrypted with the given private key
         * @throws GeneralSecurityException
         */
        public bool VerifyPassword(KeyPair keyPair, X509Certificate x509)
        {
            AgileEncryptionVerifier ver        = (AgileEncryptionVerifier)builder.GetVerifier();
            AgileEncryptionHeader   header     = (AgileEncryptionHeader)builder.GetHeader();
            HashAlgorithm           hashAlgo   = header.HashAlgorithm;
            CipherAlgorithm         cipherAlgo = header.CipherAlgorithm;
            int blockSize = header.BlockSize;

            AgileCertificateEntry ace = null;

            foreach (AgileCertificateEntry aceEntry in ver.GetCertificates())
            {
                if (x509.Equals(aceEntry.x509))
                {
                    ace = aceEntry;
                    break;
                }
            }
            if (ace == null)
            {
                return(false);
            }

            Cipher cipher = Cipher.GetInstance("RSA");

            cipher.Init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
            byte[]        keyspec   = cipher.DoFinal(ace.encryptedKey);
            SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.CipherAlgorithm.jceId);

            Mac x509Hmac = CryptoFunctions.GetMac(hashAlgo);

            x509Hmac.Init(secretKey);
            byte[] certVerifier = x509Hmac.DoFinal(ace.x509.GetEncoded());

            byte[] vec = CryptoFunctions.GenerateIv(hashAlgo, header.KeySalt, kIntegrityKeyBlock, blockSize);
            cipher = GetCipher(secretKey, cipherAlgo, ver.ChainingMode, vec, Cipher.DECRYPT_MODE);
            byte[] hmacKey = cipher.DoFinal(header.GetEncryptedHmacKey());
            hmacKey = GetBlock0(hmacKey, hashAlgo.hashSize);

            vec    = CryptoFunctions.GenerateIv(hashAlgo, header.KeySalt, kIntegrityValueBlock, blockSize);
            cipher = GetCipher(secretKey, cipherAlgo, ver.ChainingMode, vec, Cipher.DECRYPT_MODE);
            byte[] hmacValue = cipher.DoFinal(header.GetEncryptedHmacValue());
            hmacValue = GetBlock0(hmacValue, hashAlgo.hashSize);


            if (Arrays.Equals(ace.certVerifier, certVerifier))
            {
                SetSecretKey(secretKey);
                SetIntegrityHmacKey(hmacKey);
                SetIntegrityHmacValue(hmacValue);
                return(true);
            }
            else
            {
                return(false);
            }
        }
        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));
        }
    public override string ComputeSignature(string signatureBaseString, string consumerSecret)
    {
        var key       = PercentEncode(consumerSecret) + "&";
        var secretKey = new SecretKeySpec(key.GetBytes(), EncryptionMethods.HMACSHA1);

        using (Mac mac = new Mac(secretKey, signatureBaseString))
        {
            return(mac.AsBase64());
        }
    }
Example #23
0
        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);
            }
        }
Example #24
0
        /// <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 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);
            }
        }
        /// <exception cref="System.Exception"></exception>
        public virtual void Init(byte[] key)
        {
            if (key.Length > bsize)
            {
                byte[] tmp = new byte[bsize];
                System.Array.Copy(key, 0, tmp, 0, bsize);
                key = tmp;
            }
            SecretKeySpec skey = new SecretKeySpec(key, "HmacSHA1");

            mac = Mac.GetInstance("HmacSHA1");
            mac.Init(skey);
        }
Example #27
0
        /// <exception cref="System.Exception"></exception>
        public virtual void Init(byte[] key)
        {
            if (key.Length > 16)
            {
                byte[] tmp = new byte[16];
                System.Array.Copy(key, 0, tmp, 0, 16);
                key = tmp;
            }
            SecretKeySpec skey = new SecretKeySpec(key, "HmacMD5");

            mac = Mac.GetInstance("HmacMD5");
            mac.Init(skey);
        }
        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);
        }
Example #29
0
        public static string AESDecrypt(string content)
        {
            Cipher        cipher  = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(Encoding.UTF8.GetBytes(key), "AES");

            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] buffer = new byte[content.Length / 2];
            for (int i = 0; i < content.Length; i += 2)
            {
                buffer[i / 2] = Convert.ToByte(content.Substring(i, 2), 16);
            }
            byte[] data = cipher.doFinal(buffer);
            return(Encoding.UTF8.GetString(data));
        }
Example #30
0
        protected internal static ISecretKey GenerateSecretKey(String password, EncryptionVerifier ver)
        {
            if (password.Length > 255)
            {
                password = password.Substring(0, 255);
            }
            HashAlgorithm hashAlgo = ver.HashAlgorithm;
            MessageDigest hashAlg  = CryptoFunctions.GetMessageDigest(hashAlgo);

            hashAlg.Update(ver.Salt);
            byte[]     hash = hashAlg.Digest(StringUtil.GetToUnicodeLE(password));
            ISecretKey skey = new SecretKeySpec(hash, ver.CipherAlgorithm.jceId);

            return(skey);
        }