Esempio n. 1
0
        public static byte[] Decrypt(byte[] bytesToDecrypt, string password)
        {
            byte[] passwordBytes = SHA2.GetHash(password);

            (byte[] encrypted, byte[] ivSeed) = bytesToDecrypt.Pop(8);
            (byte[] key, byte[] iv)           = GetKeyAndIv(passwordBytes, ivSeed);

            byte[] decrypted = null;

            try
            {
                using (MemoryStream mStream = new MemoryStream(encrypted))
                {
                    using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
                    {
                        aesProvider.Padding = PaddingMode.None;
                        using (CryptoStream cryptoStream = new CryptoStream(mStream, aesProvider.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                        {
                            cryptoStream.Read(encrypted, 0, encrypted.Length);
                        }
                    }

                    // take only the number of bytes that were in the original byte[]
                    decrypted = mStream.ToArray();
                    decrypted = decrypted.SplitOnce(eof.ConvertToByteArray())[0];
                }
            }
            catch (Exception ex)
            {
            }

            return(decrypted);
        }
Esempio n. 2
0
        public static byte[] Encrypt(byte[] bytesToEncrypt, string password)
        {
            byte[] passwordBytes = SHA2.GetHash(password);

            bytesToEncrypt = bytesToEncrypt.Append(eof);

            byte[] ivSeed = GetRandomNumber();
            (byte[] key, byte[] iv) = GetKeyAndIv(passwordBytes, ivSeed);

            byte[] encrypted;
            using (MemoryStream mstream = new MemoryStream())
            {
                using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(mstream, aesProvider.CreateEncryptor(key, iv), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytesToEncrypt, 0, bytesToEncrypt.Length);
                    }
                }
                encrypted = mstream.ToArray();
            }

            encrypted = encrypted.Append(ivSeed);

            return(encrypted);
        }