System.Security.Cryptography.CryptoStream.Write(byte[], int, int)

Here are the examples of the csharp api System.Security.Cryptography.CryptoStream.Write(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

574 Examples 7

19 View Source File : SymetricCryptoService.cs
License : MIT License
Project Creator : ansel86castro

public byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] preplacedwordBytes)
        {
            byte[] encryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (AesManaged AES = new AesManaged())
                {

                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(AES.Key, AES.IV), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.FlushFinalBlock();
                    }
                }
                encryptedBytes = ms.ToArray();
            }

            return encryptedBytes;
        }

19 View Source File : aes.cs
License : MIT License
Project Creator : b9q

public static string decrypt_string(string encrypted_text)
        {
            // Instantiate a new Aes object to perform string symmetric encryption
            Aes encryptor = Aes.Create();

            encryptor.Mode = CipherMode.CBC;

            // Set key and IV
            byte[] aesKey = new byte[32];
            Array.Copy(key, 0, aesKey, 0, 32);
            encryptor.Key = aesKey;
            encryptor.IV = iv;

            // Instantiate a new MemoryStream object to contain the encrypted bytes
            MemoryStream memory_stream = new MemoryStream();

            // Instantiate a new encryptor from our Aes object
            ICryptoTransform aes_decryptor = encryptor.CreateDecryptor();

            // Instantiate a new CryptoStream object to process the data and write it to the 
            // memory stream
            CryptoStream crypto_stream = new CryptoStream(memory_stream, aes_decryptor, CryptoStreamMode.Write);

            // Will contain decrypted plaintext
            string plain_text = String.Empty;

            try
            {
                // Convert the ciphertext string into a byte array
                byte[] encrypted_bytes = Convert.FromBase64String(encrypted_text);

                // Decrypt the input ciphertext string
                crypto_stream.Write(encrypted_bytes, 0, encrypted_bytes.Length);

                // Complete the decryption process
                crypto_stream.FlushFinalBlock();

                // Convert the decrypted data from a MemoryStream to a byte array
                byte[] plain_bytes = memory_stream.ToArray();

                // Convert the decrypted byte array to string
                plain_text = Encoding.ASCII.GetString(plain_bytes, 0, plain_bytes.Length);
            }
            finally
            {
                // Close both the MemoryStream and the CryptoStream
                memory_stream.Close();
                crypto_stream.Close();
            }

            // Return the decrypted data as a string
            return plain_text;
        }

19 View Source File : AuthenticationController.cs
License : MIT License
Project Creator : albyho

private static string DesDecrypt(string decryptString, string decryptKey)
        {
            try
            {
                //将字符转换为UTF - 8编码的字节序列
                var rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                var rgbIV = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
                var inputByteArray = Convert.FromBase64String(decryptString);
                //用指定的密钥和初始化向量使用CBC模式的DES解密标准解密
                var dCSP = new DESCryptoServiceProvider();
                dCSP.Mode = CipherMode.CBC;
                dCSP.Padding = PaddingMode.PKCS7;
                var mStream = new MemoryStream();
                var cStream = new CryptoStream(mStream, dCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return "";
            }
        }

19 View Source File : DesEncrypt.cs
License : MIT License
Project Creator : alonsoalon

private static string Decrypt(string decryptString, string key, bool hex)
        {
            if (decryptString.IsNull())
                return null;
            if (key.IsNull())
                key = Key;
            if (key.Length < 8)
                throw new ArgumentException("秘钥长度为8位", nameof(key));

            var keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            var inputByteArray = hex ? decryptString.HexToBytes() : Convert.FromBase64String(decryptString);
            var provider = new DESCryptoServiceProvider
            {
                Mode = CipherMode.ECB,
                Key = keyBytes,
                Padding = PaddingMode.PKCS7
            };

            using (var mStream = new MemoryStream())
            {
                var cStream = new CryptoStream(mStream, provider.CreateDecryptor(), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
        }

19 View Source File : DES.cs
License : MIT License
Project Creator : albyho

public static Byte[] EncryptFromByteArrayToByteArray(Byte[] inputByteArray, CipherMode mode, PaddingMode paddingMode, string key = null)
        {
            if (inputByteArray == null)
            {
                throw new ArgumentNullException(nameof(inputByteArray));
            }

            Byte[] keyBytes = EnsureKey(key);
            Byte[] keyIV = keyBytes;
            var provider = new DESCryptoServiceProvider
            {
                Mode = mode,
                Padding = paddingMode
            };
            var mStream = new MemoryStream();
            var cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return mStream.ToArray();
        }

19 View Source File : EncryptionHelper.cs
License : MIT License
Project Creator : aishang2015

public static string DesDecrypt(string str, string key)
        {
            using (var des = DES.Create())
            {
                var array = Convert.FromBase64String(str);

                // 设置密钥和向量
                des.Key = Encoding.ASCII.GetBytes(MD5Encrypt(key).Substring(0, 8));
                des.IV = Encoding.ASCII.GetBytes(MD5Encrypt(MD5Encrypt(key)).Substring(0, 8));
                var mStream = new MemoryStream();
                var cStream = new CryptoStream(mStream, des.CreateDecryptor(), CryptoStreamMode.Write);
                cStream.Write(array, 0, array.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
        }

19 View Source File : Aes.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

private static byte[] Decrypt(
            byte[] encryptedBytes,
            byte[] keyBytes,
            int keySize = Aes256KeySize,
            int saltSize = SaltSize,
            int iterations = Iterations)
        {
            var salt = encryptedBytes.Copy(offset: 0, count: saltSize);

            using var aes = new AesManaged();
            using var key = new Rfc2898DeriveBytes(keyBytes, salt, iterations);

            aes.KeySize = keySize;
            aes.Key = key.GetBytes(cb: aes.KeySize / 8);
            aes.IV = key.GetBytes(cb: aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;

            using var ms = new MemoryStream();
            using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                cs.Write(
                    buffer: encryptedBytes,
                    offset: saltSize,
                    count: encryptedBytes.Length - saltSize);

            return ms.ToArray();
        }

19 View Source File : DesDecryptHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string DesDecryptInner(string val)
        {
            var des = new DESCryptoServiceProvider();
            var inputByteArray = Convert.FromBase64String(val);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateDecryptor(Kv, Iv), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            Encoding encoding = new UTF8Encoding();
            return encoding.GetString(ms.ToArray());
        }

19 View Source File : DES.cs
License : MIT License
Project Creator : baibao132

public string Decrypt(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

19 View Source File : DESEncrypt.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string Encrypt(string Text, string sKey = "MATICSOFT")
        {
            var des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPreplacedwordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPreplacedwordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            var ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

19 View Source File : AesEncryptor.cs
License : MIT License
Project Creator : alexanderdna

public static byte[] Encrypt(byte[] plainTextBytes, byte[] keyBytes)
        {
            if (keyBytes.Length != KeySize) throw new ArgumentException("Invalid key length", nameof(keyBytes));

            byte[] initialVectorBytes = new byte[BlockSize];
            _rand.NextBytes(initialVectorBytes);

            byte[] cipherTextBytes = null;
            using (var symmetricKey = Rijndael.Create())
            {
                symmetricKey.Mode = CipherMode.CFB;
                symmetricKey.IV = initialVectorBytes;
                symmetricKey.Key = keyBytes;
                symmetricKey.Padding = PaddingMode.Zeros;
                symmetricKey.BlockSize = BlockSize * 8;
                symmetricKey.FeedbackSize = BlockSize * 8;
                using ICryptoTransform encryptor = symmetricKey.CreateEncryptor();
                using MemoryStream memStream = new MemoryStream();
                using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                }
                cipherTextBytes = memStream.ToArray();
            }

            byte[] returnBytes = new byte[initialVectorBytes.Length + cipherTextBytes.Length];
            Array.Copy(initialVectorBytes, returnBytes, initialVectorBytes.Length);
            Array.Copy(cipherTextBytes, 0, returnBytes, initialVectorBytes.Length, cipherTextBytes.Length);

            return returnBytes;
        }

19 View Source File : DES.cs
License : MIT License
Project Creator : albyho

public static string DecryptFromBase64StringToString(string decryptBase64String, PaddingMode paddingMode, string key)
        {
            if (decryptBase64String == null)
            {
                throw new ArgumentNullException(nameof(decryptBase64String));
            }

            Byte[] inputByteArray = Convert.FromBase64String(decryptBase64String);
            Byte[] keyBytes = EnsureKey(key);
            Byte[] keyIV = keyBytes;
            var provider = new DESCryptoServiceProvider
            {
                Mode = CipherMode.ECB,
                Padding = paddingMode
            };
            var mStream = new MemoryStream();
            var cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }

19 View Source File : Encryption.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static byte[] Encrypt(byte[] data, Byte[] key, Byte[] iv)
		{
			Byte[] result = null;

			System.Security.Cryptography.TripleDES tripleDes = System.Security.Cryptography.TripleDES.Create();
			ICryptoTransform encryptor = tripleDes.CreateEncryptor(key, iv);
			using (MemoryStream ms = new MemoryStream())
			{
				using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
				{
					cs.Write(data, 0, data.Length);
					cs.Flush();	//这句很重要,在对流操作结束后必须用这句话强制将缓冲区中的数据全部写入到目标对象中  
				}
				result = ms.ToArray();
			}
			return result;
		}

19 View Source File : CCBPayUtil.cs
License : Apache License 2.0
Project Creator : anjoy8

private string DESDecrypt(string dataCharset, string data, string keyCoding, string key)
		{
			string result;
			try
			{
				byte[] bytes = Encoding.GetEncoding(keyCoding).GetBytes(key);
				byte[] rgbIV = bytes;
				byte[] array = this.Base64Decode(data);
				DESCryptoServiceProvider descryptoServiceProvider = new DESCryptoServiceProvider();
				descryptoServiceProvider.Mode = CipherMode.ECB;
				descryptoServiceProvider.Padding = PaddingMode.PKCS7;
				MemoryStream memoryStream = new MemoryStream();
				CryptoStream cryptoStream = new CryptoStream(memoryStream, descryptoServiceProvider.CreateDecryptor(bytes, rgbIV), CryptoStreamMode.Write);
				cryptoStream.Write(array, 0, array.Length);
				cryptoStream.FlushFinalBlock();
				result = Encoding.GetEncoding(dataCharset).GetString(memoryStream.ToArray());
			}
			catch
			{
				result = null;
			}
			return result;
		}

19 View Source File : Crypto.cs
License : Apache License 2.0
Project Creator : AantCoder

public static byte[] SymmetricDecrypt(byte[] cipher, string preplacedword)
        {
            MemoryStream memoryStream;
            CryptoStream cryptoStream;
            Rijndael rijndael = Rijndael.Create();
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(preplacedword, SALT);
            rijndael.Key = pdb.GetBytes(32);
            rijndael.IV = pdb.GetBytes(16);
            //rijndael.BlockSize = 128;
            memoryStream = new MemoryStream();
            cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(cipher, 0, cipher.Length);
            cryptoStream.Close();
            return memoryStream.ToArray();
        }

19 View Source File : EncryptionHandler.cs
License : Apache License 2.0
Project Creator : Appdynamics

private void EncryptAgileFromKey(EncryptionInfoAgile.EncryptionKeyEncryptor encr, byte[] key, byte[] data, long pos, long size, byte[] iv,MemoryStream ms)
        {
            var encryptKey = GetEncryptionAlgorithm(encr);
            encryptKey.BlockSize = encr.BlockSize << 3;
            encryptKey.KeySize = encr.KeyBits;
#if (Core)
            encryptKey.Mode = CipherMode.CBC;
#else
            encryptKey.Mode = encr.CipherChaining==eChainingMode.ChainingModeCBC ? CipherMode.CBC : CipherMode.CFB;
#endif
            encryptKey.Padding = PaddingMode.Zeros;

            ICryptoTransform encryptor = encryptKey.CreateEncryptor(
                                                        FixHashSize(key, encr.KeyBits / 8),
                                                        FixHashSize(iv, 16, 0x36));


            CryptoStream cryptoStream = new CryptoStream(ms,
                                                         encryptor,
                                                         CryptoStreamMode.Write);
            
            var cryptoSize = size % encr.BlockSize == 0 ? size : (size + (encr.BlockSize - (size % encr.BlockSize)));
            var buffer = new byte[size];
            Array.Copy(data, (int)pos, buffer, 0, (int)size);
            cryptoStream.Write(buffer, 0, (int)size);
            while (size % encr.BlockSize != 0)
            {
                cryptoStream.WriteByte(0);
                size++;
            }
        }

19 View Source File : AES.cs
License : MIT License
Project Creator : albyho

public static Byte[] EncryptFromByteArrayToByteArray(Byte[] inputByteArray, string key = null)
        {
            if (inputByteArray == null)
            {
                throw new ArgumentNullException(nameof(inputByteArray));
            }

            //分组加密算法
            var aes = Rijndael.Create();
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;
            aes.Key = EnsureKey(key);
            aes.IV = DefaultIV;

            Byte[] cipherBytes;
            using (var ms = new MemoryStream())
            {
                var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                cipherBytes = ms.ToArray();
            }

            return cipherBytes;
        }

19 View Source File : AyFuncSecrity.cs
License : MIT License
Project Creator : ay2015

public string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

19 View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY

private static byte[] EncryptAES(byte[] bytesToBeEncrypted, string preplacedword)
        {
            byte[] result = null;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
                {
                    rijndaelManaged.KeySize = 256;
                    rijndaelManaged.BlockSize = 128;
                    Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(Encoding.ASCII.GetBytes(preplacedword), Encoding.ASCII.GetBytes(preplacedword), 1000);
                    rijndaelManaged.Key = rfc2898DeriveBytes.GetBytes(rijndaelManaged.KeySize / 8);
                    rijndaelManaged.IV = rfc2898DeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8);
                    rijndaelManaged.Mode = CipherMode.CBC;
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cryptoStream.Close();
                    }
                    result = memoryStream.ToArray();
                }
            }
            return result;
        }

19 View Source File : DES.cs
License : MIT License
Project Creator : baibao132

public string Encrypt(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

19 View Source File : SimpleAES.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public byte[] Encrypt(string TextValue)
        {
            //Translates our text value into a byte array.
            Byte[] bytes = UTFEncoder.GetBytes(TextValue);

            //Used to stream the data in and out of the CryptoStream.
            MemoryStream memoryStream = new MemoryStream();

            /*
             * We will have to write the unencrypted bytes to the stream,
             * then read the encrypted result back from the stream.
             */
            #region Write the decrypted value to the encryption stream
            CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
            cs.Write(bytes, 0, bytes.Length);
            cs.FlushFinalBlock();
            #endregion

            #region Read encrypted value back out of the stream
            memoryStream.Position = 0;
            byte[] encrypted = new byte[memoryStream.Length];
            memoryStream.Read(encrypted, 0, encrypted.Length);
            #endregion

            //Clean up.
            cs.Close();
            memoryStream.Close();

            return encrypted;
        }

19 View Source File : SimpleAES.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public string Decrypt(byte[] EncryptedValue)
        {
            #region Write the encrypted value to the decryption stream
            MemoryStream encryptedStream = new MemoryStream();
            CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
            decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
            decryptStream.FlushFinalBlock();
            #endregion

            #region Read the decrypted value from the stream.
            encryptedStream.Position = 0;
            Byte[] decryptedBytes = new Byte[encryptedStream.Length];
            encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
            encryptedStream.Close();
            #endregion
            return UTFEncoder.GetString(decryptedBytes);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] preplacedwordBytes)
        {
            byte[] encryptedBytes = null;

            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }

19 View Source File : DES.cs
License : MIT License
Project Creator : albyho

public static string EncryptFromStringToBase64String(string encryptString, PaddingMode paddingMode, string key = null)
        {
            if (encryptString == null)
            {
                throw new ArgumentNullException(nameof(encryptString));
            }

            Byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);

            Byte[] keyBytes = EnsureKey(key);
            Byte[] keyIV = keyBytes;

            var provider = new DESCryptoServiceProvider
            {
                Mode = CipherMode.ECB,
                Padding = paddingMode
            };
            var mStream = new MemoryStream();
            var cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }

19 View Source File : DESEncrypt.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string Decrypt(string Text, string sKey = "MATICSOFT")
        {
            var des = new DESCryptoServiceProvider();
            int len = Text.Length / 2;
            var inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPreplacedwordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPreplacedwordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

19 View Source File : DataCipher.cs
License : MIT License
Project Creator : AlenToma

public string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                return plainText;
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (var preplacedword = new Rfc2898DeriveBytes(_preplacedPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = preplacedword.GetBytes(_Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = _Keysize;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

19 View Source File : AesBase.cs
License : MIT License
Project Creator : alecgn

internal AesDecryptionResult DecryptWithFileStream(string encryptedFilePath, string decryptedFilePath, byte[] key, byte[] IV, CipherMode cipherMode = CipherMode.CBC,
            PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteEncryptedFile = false, int kBbufferSize = 4, long startPosition = 0, long endPosition = 0)
        {
            if (!File.Exists(encryptedFilePath))
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Decryption_EncryptedFileNotFound} \"{encryptedFilePath}\"."
                };
            }

            if (string.IsNullOrWhiteSpace(decryptedFilePath))
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_DecryptedFilePathError
                };
            }

            var destinationDirectory = Path.GetDirectoryName(decryptedFilePath);

            if (!Directory.Exists(destinationDirectory))
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_DestinationDirectoryNotFound} \"{destinationDirectory}\"."
                };
            }

            _key = key ?? _key;
            _IV = IV ?? _IV;

            if (_key == null)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullKeyError
                };
            }

            if (_IV == null)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullIVError
                };
            }

            if (endPosition < startPosition)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = string.Format(MessageStrings.Decryption_EndPositionLessThanStartError, endPosition, startPosition)
                };
            }

            var pathsEqual = decryptedFilePath.Equals(encryptedFilePath, StringComparison.InvariantCultureIgnoreCase);

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    aesManaged.Key = _key;
                    aesManaged.IV = _IV;
                    aesManaged.Mode = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var decryptedFs = File.Open((pathsEqual ? decryptedFilePath + "_tmpdecrypt" : decryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        using (var encryptedFs = File.Open(encryptedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            encryptedFs.Position = startPosition;

                            using (var decryptor = aesManaged.CreateDecryptor(_key, _IV))
                            {
                                using (var cs = new CryptoStream(decryptedFs, decryptor, CryptoStreamMode.Write))
                                {
                                    //encrypted.CopyTo(cs);

                                    var buffer = new byte[kBbufferSize * 1024];
                                    var totalBytesToRead = ((endPosition == 0 ? encryptedFs.Length : endPosition) - startPosition);
                                    var totalBytesNotRead = totalBytesToRead;
                                    long totalBytesRead = 0;
                                    var percentageDone = 0;

                                    while (totalBytesNotRead > 0)
                                    {
                                        var bytesRead = encryptedFs.Read(buffer, 0, (int)Math.Min(buffer.Length, totalBytesNotRead));

                                        if (bytesRead > 0)
                                        {
                                            cs.Write(buffer, 0, bytesRead);

                                            totalBytesRead += bytesRead;
                                            totalBytesNotRead -= bytesRead;
                                            var tmpPercentageDone = (int)(totalBytesRead * 100 / totalBytesToRead);

                                            if (tmpPercentageDone != percentageDone)
                                            {
                                                percentageDone = tmpPercentageDone;

                                                RaiseOnDecryptionProgress(percentageDone, (percentageDone != 100 ? $"Decrypting ({percentageDone}%)..." : $"Decrypted ({percentageDone}%)."));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(encryptedFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(encryptedFilePath);
                    File.Move(decryptedFilePath + "_tmpdecrypt", decryptedFilePath);
                }

                if (deleteEncryptedFile && !pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(encryptedFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(encryptedFilePath);
                }

                var message = string.Format(MessageStrings.Decryption_FileDecryptSuccess, encryptedFilePath, decryptedFilePath);
                message += (deleteEncryptedFile && !pathsEqual ? $"\n{string.Format(MessageStrings.Encryption_FileDeleted, encryptedFilePath)}" : "");

                return new AesDecryptionResult()
                {
                    Success = true,
                    Message = message,
                    Key = _key,
                    IV = _IV,
                    AesCipherMode = (AesCipherMode)cipherMode,
                    PaddingMode = paddingMode
                };
            }
            catch (Exception ex)
            {
                return new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Decryption_ExceptionError}\n{ex.ToString()}"
                };
            }
        }

19 View Source File : Encryption.cs
License : MIT License
Project Creator : ahmed-abdelrazek

private static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] preplacedwordBytes)
        {
            byte[] decryptedBytes = null;
            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            using (MemoryStream ms = new())
            {
                using (RijndaelManaged AES = new())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);
                    AES.Mode = CipherMode.CBC;
                    using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
            }
            return decryptedBytes;
        }

19 View Source File : DesEncrypt.cs
License : MIT License
Project Creator : alonsoalon

private static string Encrypt(string encryptString, string key, bool hex, bool lowerCase = false)
        {
            if (encryptString.IsNull())
                return null;
            if (key.IsNull())
                key = Key;
            if (key.Length < 8)
                throw new ArgumentException("秘钥长度为8位", nameof(key));

            var keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            var inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            var provider = new DESCryptoServiceProvider
            {
                Mode = CipherMode.ECB,
                Key = keyBytes,
                Padding = PaddingMode.PKCS7
            };

            using (var stream = new MemoryStream())
            {
                var cStream = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();

                var bytes = stream.ToArray();
                return hex ? bytes.ToHex(lowerCase) : bytes.ToBase64();
            }
        }

19 View Source File : Crypto.cs
License : Apache License 2.0
Project Creator : AantCoder

public static byte[] SymmetricEncrypt(byte[] plain, string preplacedword)
        {
            MemoryStream memoryStream;
            CryptoStream cryptoStream;
            Rijndael rijndael = Rijndael.Create();
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(preplacedword, SALT);
            rijndael.Key = pdb.GetBytes(32);
            rijndael.IV = pdb.GetBytes(16);
            //rijndael.BlockSize = 128;
            memoryStream = new MemoryStream();
            cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(plain, 0, plain.Length);
            cryptoStream.Close();
            return memoryStream.ToArray();
        }

19 View Source File : CCBPayUtil.cs
License : Apache License 2.0
Project Creator : anjoy8

private byte[] DESEncrypt(string dataCharset, string data, string keyCharset, string key)
		{
			byte[] result;
			try
			{
				byte[] bytes = Encoding.GetEncoding(keyCharset).GetBytes(key);
				byte[] rgbIV = bytes;
				byte[] bytes2 = Encoding.GetEncoding(dataCharset).GetBytes(data);
				DESCryptoServiceProvider descryptoServiceProvider = new DESCryptoServiceProvider();
				descryptoServiceProvider.Mode = CipherMode.ECB;
				descryptoServiceProvider.Padding = PaddingMode.PKCS7;
				MemoryStream memoryStream = new MemoryStream();
				CryptoStream cryptoStream = new CryptoStream(memoryStream, descryptoServiceProvider.CreateEncryptor(bytes, rgbIV), CryptoStreamMode.Write);
				cryptoStream.Write(bytes2, 0, bytes2.Length);
				cryptoStream.FlushFinalBlock();
				result = memoryStream.ToArray();
			}
			catch
			{
				result = null;
			}
			return result;
		}

19 View Source File : EncryptionHelper.cs
License : MIT License
Project Creator : aishang2015

public static string DesEncrypt(string str, string key)
        {
            using (var des = DES.Create())
            {
                var array = Encoding.UTF8.GetBytes(str);

                // 设置密钥和向量
                des.Key = Encoding.ASCII.GetBytes(MD5Encrypt(key).Substring(0, 8));
                des.IV = Encoding.ASCII.GetBytes(MD5Encrypt(MD5Encrypt(key)).Substring(0, 8));
                var mStream = new MemoryStream();
                var cStream = new CryptoStream(mStream, des.CreateEncryptor(), CryptoStreamMode.Write);
                cStream.Write(array, 0, array.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
        }

19 View Source File : SymetricCryptoService.cs
License : MIT License
Project Creator : ansel86castro

public override byte[] Encrypt(byte[] source)
        {

            using (RijndaelManaged myRijndael = new RijndaelManaged())
            {
                if (Key == null)
                {
                    myRijndael.GenerateKey();
                    Key = myRijndael.Key;
                    KeySize = myRijndael.KeySize;
                }
                else
                {
                    myRijndael.Key = Key;
                }

                if (IV == null)
                {
                    myRijndael.GenerateIV();
                    IV = myRijndael.IV;
                }
                else
                {
                    myRijndael.IV = IV;
                }

                // Encrypt the string to an array of bytes.
                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = myRijndael.CreateEncryptor(myRijndael.Key, myRijndael.IV);

                byte[] encrypted;
                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(source, 0, source.Length);
                        csEncrypt.FlushFinalBlock();
                        encrypted = msEncrypt.ToArray();
                    }
                }

                return encrypted;
            }
        }

19 View Source File : AesEncrypt.cs
License : MIT License
Project Creator : 17MKH

private string Encrypt(string encryptString, string key, bool hex, bool lowerCase = false)
    {
        if (encryptString.IsNull())
            return null;
        if (key.IsNull())
            key = KEY;

        var keyBytes = Encoding.UTF8.GetBytes(key);
        var encryptBytes = Encoding.UTF8.GetBytes(encryptString);
        var provider = new RijndaelManaged
        {
            Mode = CipherMode.ECB,
            Key = keyBytes,
            Padding = PaddingMode.PKCS7
        };

        using var stream = new MemoryStream();
        var cStream = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
        cStream.Write(encryptBytes, 0, encryptBytes.Length);
        cStream.FlushFinalBlock();

        var bytes = stream.ToArray();
        return hex ? bytes.ToHex(lowerCase) : bytes.ToBase64();
    }

19 View Source File : EncryptionHandler.cs
License : Apache License 2.0
Project Creator : Appdynamics

private byte[] EncryptData(byte[] key, byte[] data, bool useDataSize)
        {
#if (Core)
            var aes = Aes.Create();
#else
            RijndaelManaged aes = new RijndaelManaged();
#endif
            aes.KeySize = key.Length * 8;
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.Zeros;

            //Encrypt the data
            var crypt = aes.CreateEncryptor(key, null);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, crypt, CryptoStreamMode.Write);
            cs.Write(data, 0, data.Length);

            cs.FlushFinalBlock();

            byte[] ret;
            if (useDataSize)
            {
                ret = new byte[data.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(ret, 0, data.Length);  //Truncate any padded Zeros
                return ret;
            }
            else
            {
                return ms.ToArray();
            }
        }

19 View Source File : AES.cs
License : MIT License
Project Creator : albyho

public static Byte[] EncryptFromByteArrayToByteArray(Byte[] inputByteArray, PaddingMode padding, CipherMode mode, string key = null)
        {
            if (inputByteArray == null)
            {
                throw new ArgumentNullException(nameof(inputByteArray));
            }

            //分组加密算法
            var aes = Rijndael.Create();
            aes.Padding = padding;
            aes.Mode = mode;
            aes.Key = EnsureKey(key);
            aes.IV = DefaultIV;

            Byte[] cipherBytes;
            using (var ms = new MemoryStream())
            {
                var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                cipherBytes = ms.ToArray();
            }
            return cipherBytes;
        }

19 View Source File : Aes.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

private static byte[] Encrypt(
            byte[] plainBytes,
            byte[] keyBytes,
            int keySize = Aes256KeySize,
            int saltSize = SaltSize,
            int iterations = Iterations)
        {
            var salt = Rand.SecureRandomBytes(length: saltSize);

            using var aes = new AesManaged();
            using var key = new Rfc2898DeriveBytes(keyBytes, salt, iterations);

            aes.KeySize = keySize;
            aes.Key = key.GetBytes(cb: aes.KeySize / 8);
            aes.IV = key.GetBytes(cb: aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;

            using var ms = new MemoryStream();
            ms.Write(buffer: salt, offset: 0, count: salt.Length);

            using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                cs.Write(buffer: plainBytes, offset: 0, count: plainBytes.Length);

            return ms.ToArray();
        }

19 View Source File : SimpleAES.cs
License : GNU General Public License v3.0
Project Creator : aelariane

protected byte[] Transform(byte[] buffer, ICryptoTransform transform)
    {
        MemoryStream memoryStream = new MemoryStream();
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
        {
            cryptoStream.Write(buffer, 0, buffer.Length);
        }
        return memoryStream.ToArray();
    }

19 View Source File : AyFuncSecrity.cs
License : MIT License
Project Creator : ay2015

public string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

19 View Source File : DES.cs
License : MIT License
Project Creator : albyho

public static Byte[] DecryptFromByteArrayToByteArray(Byte[] inputByteArray, CipherMode mode, PaddingMode paddingMode, string key = null)
        {
            if (inputByteArray == null)
            {
                throw new ArgumentNullException(nameof(inputByteArray));
            }

            Byte[] keyBytes = EnsureKey(key);
            Byte[] keyIV = keyBytes;
            var provider = new DESCryptoServiceProvider
            {
                Mode = mode,
                Padding = paddingMode
            };
            var mStream = new MemoryStream();
            var cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return mStream.ToArray();
        }

19 View Source File : aes.cs
License : MIT License
Project Creator : b9q

public static string encrypt_string(string plain_text)
        {
            // Instantiate a new Aes object to perform string symmetric encryption
            Aes encryptor = Aes.Create();

            encryptor.Mode = CipherMode.CBC;

            // Set key and IV
            byte[] aes_key = new byte[32];
            Array.Copy(key, 0, aes_key, 0, 32);
            encryptor.Key = aes_key;
            encryptor.IV = iv;

            // Instantiate a new MemoryStream object to contain the encrypted bytes
            MemoryStream memory_stream = new MemoryStream();

            // Instantiate a new encryptor from our Aes object
            ICryptoTransform aes_encryptor = encryptor.CreateEncryptor();

            // Instantiate a new CryptoStream object to process the data and write it to the 
            // memory stream
            CryptoStream crypto_stream = new CryptoStream(memory_stream, aes_encryptor, CryptoStreamMode.Write);

            // Convert the plainText string into a byte array
            byte[] plain_bytes = Encoding.ASCII.GetBytes(plain_text);

            // Encrypt the input plaintext string
            crypto_stream.Write(plain_bytes, 0, plain_bytes.Length);

            // Complete the encryption process
            crypto_stream.FlushFinalBlock();

            // Convert the encrypted data from a MemoryStream to a byte array
            byte[] cipherBytes = memory_stream.ToArray();

            // Close both the MemoryStream and the CryptoStream
            memory_stream.Close();
            crypto_stream.Close();

            // Convert the encrypted byte array to a base64 encoded string
            string encrypted_text = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);

            // Return the encrypted data as a string
            return encrypted_text;
        }

19 View Source File : cAES256.cs
License : MIT License
Project Creator : 0xPh0enix

public static byte[] Encrypt(byte[] bData, byte[] bKey)
        {
            byte[] bEncrypted = null;

            using (MemoryStream mStream = new MemoryStream())
            {
                using (RijndaelManaged rmAES = new RijndaelManaged())
                {
                    rmAES.KeySize = 256;
                    rmAES.BlockSize = 128;

                    Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(bKey, bSalt, 1000);

                    rmAES.Key = rfcKey.GetBytes(rmAES.KeySize / 8);
                    rmAES.IV = rfcKey.GetBytes(rmAES.BlockSize / 8);

                    rmAES.Mode = CipherMode.CBC;

                    using (CryptoStream cStream = new CryptoStream(mStream, rmAES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bData, 0, bData.Length);
                        cStream.Close();
                    }
                    bEncrypted = mStream.ToArray();
                }
            }

            return bEncrypted;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : b9q

private static void encrypt_file(string input_file, string output_file, string preplacedword)
        {
            byte[] array = generate_random_salt();
            FileStream file_stream = new FileStream(output_file, FileMode.Create);
            byte[] bytes = Encoding.UTF8.GetBytes(preplacedword);
            RijndaelManaged rij_managed = new RijndaelManaged();
            rij_managed.KeySize = 256;
            rij_managed.BlockSize = 128;
            rij_managed.Padding = PaddingMode.PKCS7;
            Rfc2898DeriveBytes rfc_derive = new Rfc2898DeriveBytes(bytes, array, 50000);
            rij_managed.Key = rfc_derive.GetBytes(rij_managed.KeySize / 8);
            rij_managed.IV = rfc_derive.GetBytes(rij_managed.BlockSize / 8);
            rij_managed.Mode = CipherMode.CFB;
            file_stream.Write(array, 0, array.Length);
            CryptoStream crypto_stream = new CryptoStream(file_stream, rij_managed.CreateEncryptor(), CryptoStreamMode.Write);
            FileStream file_stream_2 = new FileStream(input_file, FileMode.Open);
            byte[] array2 = new byte[1048576];
            int count;
            while ((count = file_stream_2.Read(array2, 0, array2.Length)) > 0)
            {
                crypto_stream.Write(array2, 0, count);
            }
            file_stream_2.Close();
            crypto_stream.Close();
            file_stream.Close();
        }

19 View Source File : AesBase.cs
License : MIT License
Project Creator : alecgn

internal AesEncryptionResult EncryptWithFileStream(string sourceFilePath, string encryptedFilePath, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC,
            PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteSourceFile = false, int kBbufferSize = 4)
        {
            if (!File.Exists(sourceFilePath))
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    //Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"."
                    Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"."
                };
            }

            if (string.IsNullOrWhiteSpace(encryptedFilePath))
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Encryption_EncryptedFilePathError
                };
            }

            var destinationDirectory = Path.GetDirectoryName(encryptedFilePath);

            if (!Directory.Exists(destinationDirectory))
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_DestinationDirectoryNotFound} \"{destinationDirectory}\"."
                };
            }

            _key = key ?? _key;
            _IV = IV ?? _IV;

            var pathsEqual = encryptedFilePath.Equals(sourceFilePath, StringComparison.InvariantCultureIgnoreCase);

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    if (_key == null)
                    {
                        aesManaged.GenerateKey();
                        _key = aesManaged.Key;
                    }
                    else
                    {
                        if (aesManaged.ValidKeySize((_key.Length * 8)))
                        {
                            aesManaged.Key = _key;
                        }
                        else
                        {
                            return new AesEncryptionResult()
                            {
                                Success = false,
                                Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})."
                            };
                        }
                    }

                    if (_IV == null || _IV.Length == 0)
                    {
                        aesManaged.GenerateIV();
                        _IV = aesManaged.IV;
                    }
                    else
                    {
                        aesManaged.IV = _IV;
                    }

                    aesManaged.Mode = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var encryptor = aesManaged.CreateEncryptor(_key, _IV))
                    {
                        using (var sourceFs = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            using (var encryptedFs = File.Open((pathsEqual ? encryptedFilePath + "_tmpcrypt" : encryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                using (var cs = new CryptoStream(encryptedFs, encryptor, CryptoStreamMode.Write))
                                {
                                    //plain.CopyTo(cs);

                                    var buffer = new byte[kBbufferSize * 1024];
                                    int read;
                                    var percentageDone = 0;

                                    while ((read = sourceFs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        cs.Write(buffer, 0, read);

                                        var tmpPercentageDone = (int)(sourceFs.Position * 100 / sourceFs.Length);

                                        if (tmpPercentageDone != percentageDone)
                                        {
                                            percentageDone = tmpPercentageDone;

                                            RaiseOnEncryptionProgress(percentageDone, (percentageDone != 100 ? $"Encrypting ({percentageDone}%)..." : $"Encrypted ({percentageDone}%)."));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(sourceFilePath);
                    File.Move(encryptedFilePath + "_tmpcrypt", encryptedFilePath);
                }

                if (deleteSourceFile && !pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(sourceFilePath);
                }

                //var message = $"File \"{sourceFilePath}\" successfully encrypted to \"{encryptedFilePath}\".";
                var message = string.Format(MessageStrings.Encryption_FileEncryptSuccess, sourceFilePath, encryptedFilePath);
                message += (deleteSourceFile && !pathsEqual ? $"\n{string.Format(MessageStrings.Encryption_FileDeleted, sourceFilePath)}" : "");

                return new AesEncryptionResult()
                {
                    Success = true,
                    Message = message,
                    Key = _key,
                    IV = _IV,
                    AesCipherMode = (AesCipherMode)cipherMode,
                    PaddingMode = paddingMode
                };
            }
            catch (Exception ex)
            {
                return new AesEncryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_ExceptionError}\n{ex.ToString()}"
                };
            }
        }

19 View Source File : DesDecryptHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string EncryptorInner(string val)
        {
            var des = new DESCryptoServiceProvider();
            var inputByteArray = Encoding.UTF8.GetBytes(val);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateEncryptor(Kv, Iv), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }

19 View Source File : Encryption.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

public static string Encrypt<T>(string value, string preplacedword)
                where T : SymmetricAlgorithm, new()
        {
            byte[] vectorBytes = ASCIIEncoding.ASCII.GetBytes(_vector);
            byte[] saltBytes = ASCIIEncoding.ASCII.GetBytes(_salt);
            byte[] valueBytes = UTF8Encoding.UTF8.GetBytes(value);

            byte[] encrypted;
            using (T cipher = new T())
            {
                PreplacedwordDeriveBytes _preplacedwordBytes =
                    new PreplacedwordDeriveBytes(preplacedword, saltBytes, _hash, _iterations);
                byte[] keyBytes = _preplacedwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes))
                {
                    using (MemoryStream to = new MemoryStream())
                    {
                        using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write))
                        {
                            writer.Write(valueBytes, 0, valueBytes.Length);
                            writer.FlushFinalBlock();
                            encrypted = to.ToArray();
                        }
                    }
                }
                cipher.Clear();
            }
            return Convert.ToBase64String(encrypted);
        }

19 View Source File : cMain.cs
License : MIT License
Project Creator : 0xPh0enix

public static byte[] Decrypt(byte[] bData, byte[] bKey)
        {
            byte[] bDecrypted = null;

            using (MemoryStream mStream = new MemoryStream())
            {
                using (RijndaelManaged rmAES = new RijndaelManaged())
                {
                    rmAES.KeySize = 256;
                    rmAES.BlockSize = 128;

                    Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(bKey, bSalt, 1000);

                    rmAES.Key = rfcKey.GetBytes(rmAES.KeySize / 8);
                    rmAES.IV = rfcKey.GetBytes(rmAES.BlockSize / 8);

                    rmAES.Mode = CipherMode.CBC;

                    using (CryptoStream cStream = new CryptoStream(mStream, rmAES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bData, 0, bData.Length);
                        cStream.Close();
                    }

                    bDecrypted = mStream.ToArray();
                }
            }

            return bDecrypted;
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] preplacedwordBytes)
        {
            byte[] decryptedBytes = null;
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
            }

            return decryptedBytes;
        }

19 View Source File : Encryption.cs
License : MIT License
Project Creator : ahmed-abdelrazek

private static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] preplacedwordBytes)
        {
            byte[] encryptedBytes = null;
            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            using (MemoryStream ms = new())
            {
                using (RijndaelManaged AES = new())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);
                    AES.Mode = CipherMode.CBC;
                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }
            return encryptedBytes;
        }

19 View Source File : ByteCipher.cs
License : MIT License
Project Creator : AlenToma

public byte[] Encrypt(byte[] plainTextBytes)
        {
            if (plainTextBytes.Length <= 0)
                return plainTextBytes;

            using (var preplacedword = new Rfc2898DeriveBytes(_preplacedPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = preplacedword.GetBytes(_Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = _Keysize;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return cipherTextBytes;
                            }
                        }
                    }
                }
            }
        }

See More Examples