Flush() public method

public Flush ( ) : void
return void
Ejemplo n.º 1
0
        public static MemoryStream GetDeCryptedMemoryStream(string outputFilePath, string password = "******")
        {
            var ms = new MemoryStream();

            var inFile = new FileStream(outputFilePath, FileMode.Open, FileAccess.Read);

            var algorithm = GetAlgorithm(password);

            //There could be a case, where more data is appended than required, as a result Serialization fails
            //var length = inFile.Length > 1024 ? 1024 : inFile.Length;
            var length = 1;
            var fileData = new byte[length];

            var encryptedStream = new CryptoStream(inFile, algorithm.CreateDecryptor(), CryptoStreamMode.Read);

            while (encryptedStream.Read(fileData, 0, fileData.Length) != 0)
            {
                ms.Write(fileData, 0, fileData.Length);
            }

            encryptedStream.Flush();
            encryptedStream.Close();
            inFile.Close();

            ms.Position = 0;

            return ms;
        }
Ejemplo n.º 2
0
        /// <summary> 
        /// Decrypt a string 
        /// </summary> 
        /// <param name="input">Input string in base 64 format</param> 
        /// <returns>Decrypted string</returns> 
        public static string Decrypt(string input, string password)
        {
            byte[] encryptedBytes = Convert.FromBase64String(input);
            byte[] saltBytes = Encoding.UTF8.GetBytes(password);
            string decryptedString = string.Empty;
            using (var aes = new AesManaged())
            {
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;
                aes.Key = rfc.GetBytes(aes.KeySize / 8);
                aes.IV = rfc.GetBytes(aes.BlockSize / 8);

                using (ICryptoTransform decryptTransform = aes.CreateDecryptor())
                {
                    using (MemoryStream decryptedStream = new MemoryStream())
                    {
                        CryptoStream decryptor =
                            new CryptoStream(decryptedStream, decryptTransform, CryptoStreamMode.Write);
                        decryptor.Write(encryptedBytes, 0, encryptedBytes.Length);
                        decryptor.Flush();
                        decryptor.Close();

                        byte[] decryptBytes = decryptedStream.ToArray();
                        decryptedString =
                            UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
                    }
                }
            }

            return decryptedString;
        }
Ejemplo n.º 3
0
        public static string Encrypt(string key, string text)
        {
            // Our symmetric encryption algorithm
            AesManaged aes = new AesManaged();

            // We're using the PBKDF2 standard for password-based key generation
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("password", Encoding.UTF8.GetBytes(key));

            // Setting our parameters
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;

            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

            // Encryption
            ICryptoTransform encryptTransf = aes.CreateEncryptor();

            // Output stream, can be also a FileStream
            MemoryStream encryptStream = new MemoryStream();
            CryptoStream encryptor = new CryptoStream(encryptStream, encryptTransf, CryptoStreamMode.Write);

            byte[] utfData = Encoding.Unicode.GetBytes(text);

            encryptor.Write(utfData, 0, utfData.Length);
            encryptor.Flush();
            encryptor.Close();

            // return encrypted content
            return Convert.ToBase64String(encryptStream.ToArray());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Encrypt(string password)
        {
            byte[] utfData = UTF8Encoding.UTF8.GetBytes(password);
            byte[] saltBytes = Encoding.UTF8.GetBytes("Element5");
            string encryptedString = string.Empty;
            using (AesManaged aes = new AesManaged())
            {
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);

                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;
                aes.Key = rfc.GetBytes(aes.KeySize / 8);
                aes.IV = rfc.GetBytes(aes.BlockSize / 8);

                using (ICryptoTransform encryptTransform = aes.CreateEncryptor())
                {
                    using (MemoryStream encryptedStream = new MemoryStream())
                    {
                        using (CryptoStream encryptor =
                            new CryptoStream(encryptedStream, encryptTransform, CryptoStreamMode.Write))
                        {
                            encryptor.Write(utfData, 0, utfData.Length);
                            encryptor.Flush();
                            encryptor.Close();

                            byte[] encryptBytes = encryptedStream.ToArray();
                            encryptedString = Convert.ToBase64String(encryptBytes);
                            encryptedString = encryptedString.Substring(0, 20);
                        }
                    }
                }
            }
            return encryptedString;
        }
Ejemplo n.º 5
0
 public string Decrypt(byte[] key, string encryptedString)
 {
     // Initialize
     AesManaged decryptor = new AesManaged();
     byte[] encryptedData = Convert.FromBase64String(encryptedString);
     // Set the key
     decryptor.Key = key;
     decryptor.IV = key;
     // create a memory stream
     using (MemoryStream decryptionStream = new MemoryStream())
     {
         // Create the crypto stream
         using (
             CryptoStream decrypt = new CryptoStream(decryptionStream, decryptor.CreateDecryptor(),
                 CryptoStreamMode.Write))
         {
             // Encrypt
             decrypt.Write(encryptedData, 0, encryptedData.Length);
             decrypt.Flush();
             decrypt.Close();
             // Return the unencrypted data
             byte[] decryptedData = decryptionStream.ToArray();
             return UTF8Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
         }
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Decrypt a Base64 string using Triple Data Encryption Standard(TDES) 256 bit symmetric encryption format
        /// and returns the decrypted string. The decryption key is generated based on the FiWare
        /// framework assembly public key.
        /// </summary>
        /// <param name="valueToDecrypt">Input String to decrypy in Base64 format.</param>
        /// <returns>Decrypted output string.</returns>
        public string DecryptString(string valueToDecrypt)
        {
            using (MemoryStream decryVal = new MemoryStream())
            {
                using (TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider())
                {
                    symKey = new byte[24];
                    symIV = new byte[8];
                    byte[] publicKey = Assembly.GetExecutingAssembly().GetName().GetPublicKey();
                    Encoding encoding = Encoding.UTF8;

                    string keyValue = encoding.GetString(publicKey);
                    GenerateKeyVector(keyValue);
                    cryptoProvider.Key = symKey;
                    cryptoProvider.IV = symIV;

                    using (ICryptoTransform cryptoTrans = cryptoProvider.CreateDecryptor())
                    {
                        using (CryptoStream cryptoStreamDecr = new CryptoStream(decryVal, cryptoTrans, CryptoStreamMode.Write))
                        {
                            byte[] arrayInput = Convert.FromBase64String(valueToDecrypt);
                            cryptoStreamDecr.Write(arrayInput, 0, arrayInput.Length);
                            cryptoStreamDecr.Flush();
                        }
                    }

                    return encoding.GetString(decryVal.ToArray());
                }
            }
        }
Ejemplo n.º 7
0
        public static bool EncryptFile(string alg, string key, string srcFile, string dstFile)
        {
            try
            {
                SymmetricAlgorithm cipher = SymmetricAlgorithm.Create(alg);
                cipher.Key = Encoding.Default.GetBytes(key);
                cipher.IV = cipher.Key;

                FileStream iStream = File.OpenRead(srcFile);
                FileStream oStream = new FileStream(dstFile, FileMode.Create);

                CryptoStream cStream = new CryptoStream(oStream, cipher.CreateEncryptor(), CryptoStreamMode.Write);
                byte[] buffer = new byte[4096];
                int len = iStream.Read(buffer, 0, buffer.Length);
                while (len > 0)
                {
                    cStream.Write(buffer, 0, len);
                    len = iStream.Read(buffer, 0, buffer.Length);
                }

                cStream.Flush();
                cStream.Close();

                oStream.Close();
                iStream.Close();

                return true;
            }
            catch
            {
                return false;
            }
        }
Ejemplo n.º 8
0
        public string Encrypt(string data)
        {
            try
            {
                List<byte> hexString = new List<byte>(Encoding.Default.GetBytes(data));
                while (hexString.Count % 16 != 0)
                {
                    hexString.Add(0x00);
                }
                _rijndael.Key = _chatKey;

                CryptoStream stream = new CryptoStream(new MemoryStream(hexString.ToArray()), _rijndael.CreateEncryptor(), CryptoStreamMode.Read);
                MemoryStream textBytes = new MemoryStream();
#if NET20 || NET35
                byte[] buffer = new byte[1024];
                int read = stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                textBytes.Write(buffer, 0, read);
#else
                stream.CopyTo(textBytes);
#endif
                return Convert.ToBase64String(textBytes.ToArray());
            }
            catch (CryptographicException e)
            {
                Debug.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Encrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="plaintext">The message (plaintext) to encrypt</param>
        /// <param name="key">An AES key</param>
        /// <param name="iv">The IV to use or null to use a 0 IV</param>
        /// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
        /// before it is encrypted.</param>
        /// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
        public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
        {
            using (Aes aes =Aes.Create())
//            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;
                aes.Mode = CipherMode.CBC;
                aes.IV = iv;

                // Encrypt the message with the key using CBC and InitializationVector=0
                byte[] cipherText;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        if (addHmac)
                        {
                            byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
                            cs.Write(hmac, 0, hmac.Length);
                        }
                        cs.Flush();
                    }
                    cipherText = ciphertext.ToArray();
                }

                return cipherText;
            }
        }
        /// <summary>
        /// Metoda za simetrično kriptiranje
        /// </summary>
        /// <param name="file"></param>
        public void SyncCrypt(string file)
        {
            string zapis;
            zapis = file + ".ecb";
            FileStream fstreamU = File.OpenRead(file),
            fstreamO = File.OpenWrite(zapis);
            long lSize = fstreamU.Length;

            byte[] bytes = new byte[BufferSize];
            int read = -1;

            Rijndael rijndaelAlg = Rijndael.Create();
            rijndaelAlg.Mode = CipherMode.ECB;
            TextReader streamreader = new StreamReader("tajni_kljuc.txt");
            string secretKey = streamreader.ReadLine();
            rijndaelAlg.Key = Convert.FromBase64String(secretKey);
            streamreader.Close();

            CryptoStream cout = new CryptoStream(fstreamO, rijndaelAlg.CreateEncryptor(), CryptoStreamMode.Write);

            BinaryWriter bw = new BinaryWriter(cout);
            bw.Write(lSize);

            while ((read = fstreamU.Read(bytes, 0, bytes.Length)) != 0)
            {
                cout.Write(bytes, 0, read);
            }

            cout.Flush();
            cout.Close();
            cout.Dispose();
            fstreamU.Flush();
            fstreamU.Close();
            fstreamU.Dispose();
        }
Ejemplo n.º 11
0
        EncryptedValue IEncryptionService.Encrypt(string value)
        {
            if (Key == null)
                throw new InvalidOperationException("Cannot encrypt because a Key was not configured. Please specify 'RijndaelEncryptionServiceConfig' in your application's configuration file.");

            using (var rijndael = new RijndaelManaged())
            {
                rijndael.Key = Key;
                rijndael.Mode = CipherMode.CBC;
                rijndael.GenerateIV();

                using (var encryptor = rijndael.CreateEncryptor())
                using (var memoryStream = new MemoryStream())
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                using (var writer = new StreamWriter(cryptoStream))
                {
                    writer.Write(value);
                    writer.Flush();
                    cryptoStream.Flush();
                    cryptoStream.FlushFinalBlock();
                    return new EncryptedValue
                    {
                        EncryptedBase64Value = Convert.ToBase64String(memoryStream.ToArray()),
                        Base64Iv = Convert.ToBase64String(rijndael.IV)
                    };
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Decrypt encrypted string
        /// </summary>
        /// <param name="Str">Encrypted string</param>
        /// <param name="Password">Password used for encryption</param>
        /// <param name="Salt">Salt string used for encryption (at least 8 bytes)</param>
        /// <returns>Decrypted string if success; otherwise - empty string</returns>
        public static string DecryptString(string Str, string Password = "******", string Salt = "tdcm1234")
        {
            try
            {
                using (Aes aes = new AesManaged())
                {
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt));
                    aes.Key = deriveBytes.GetBytes(128 / 8);
                    aes.IV = aes.Key;

                    using (MemoryStream decryptionStream = new MemoryStream())
                    {
                        using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            byte[] encryptedData = Convert.FromBase64String(Str);
                            decrypt.Write(encryptedData, 0, encryptedData.Length);
                            decrypt.Flush();
                        }
                        byte[] decryptedData = decryptionStream.ToArray();
                        return UTF8Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error : AES ~ DecryptString ; " + ex.Message);
                return "";
            }
        }
Ejemplo n.º 13
0
		public EncryptedValue Encrypt(string value)
		{
			using (var rijndael = new RijndaelManaged())
			{
				rijndael.Key = Key;
				rijndael.Mode = CipherMode.CBC;
				rijndael.GenerateIV();

				using (var encryptor = rijndael.CreateEncryptor())
				using (var memoryStream = new MemoryStream())
				using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
				using (var writer = new StreamWriter(cryptoStream))
				{
					writer.Write(value);
					writer.Flush();
					cryptoStream.Flush();
					cryptoStream.FlushFinalBlock();
					return new EncryptedValue
					{
                        EncryptedBase64Value = Convert.ToBase64String(memoryStream.ToArray()),
						Base64Iv = Convert.ToBase64String(rijndael.IV)
					};
				}
			}
		}
Ejemplo n.º 14
0
        public static void EncryptFile(string strInFile, string strOutFile)
        {
            // Create a file pointer to the text file to encrypt.
            FileStream fileInText = new FileStream(strInFile,FileMode.Open, FileAccess.Read);

            // Create a file pointer for the encrypted output file.
            FileStream fileOutEncrypted = new FileStream(strOutFile, FileMode.Create, FileAccess.Write);

            // Start encryption service and provided string parameter as key.
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(KEY);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(KEY);
            ICryptoTransform desencrypt = DES.CreateEncryptor();

            // Links the key and the data in a stream.
            CryptoStream cryptostream = new CryptoStream(fileOutEncrypted,desencrypt,CryptoStreamMode.Write);

            byte[] bytearrayInput = new byte[fileInText.Length];

            fileInText.Read(bytearrayInput, 0, bytearrayInput.Length);
            cryptostream.Write(bytearrayInput, 0, bytearrayInput.Length);
            cryptostream.Flush();
            cryptostream.Close();
            fileInText.Close();
        }
Ejemplo n.º 15
0
        public void FullByteRangeTest()
        {
            //writing
            MemoryStream ms = new MemoryStream();  //this could be any stream we want to write to

            YEncEncoder encoder = new YEncEncoder();
            CryptoStream cs = new CryptoStream(ms, encoder, CryptoStreamMode.Write);

            byte[] bytes = new byte[256];
            for(int i=byte.MinValue; i<=byte.MaxValue; i++)
            {
                bytes[i] = (byte)i;
            }

            BinaryWriter w = new BinaryWriter(cs);
            w.Write(bytes, 0, 256);
            w.Flush();
            cs.Flush();

            //reading back from the memorystream
            ms.Position = 0;
            YEncDecoder decoder = new YEncDecoder();
            CryptoStream cs2 = new CryptoStream(ms, decoder, CryptoStreamMode.Read);

            BinaryReader r = new BinaryReader(cs2);
            byte[] newBytes = r.ReadBytes(256);

            Assert.AreEqual(BitConverter.ToString(bytes, 0, 256), BitConverter.ToString(newBytes, 0, 256));
        }
Ejemplo n.º 16
0
		/// <summary>
		/// Serializes this <see cref="Token"/> instance as a string that can be
		/// included as part of a return_to variable in a querystring. 
		/// This string is cryptographically signed to protect against tampering.
		/// </summary>
		public string Serialize(INonceStore store) {
			using (MemoryStream dataStream = new MemoryStream()) {
				if (!persistSignature(store)) {
					Debug.Assert(!persistNonce(Endpoint, store), "Without a signature, a nonce is meaningless.");
					dataStream.WriteByte(0); // there will be NO signature.
					StreamWriter writer = new StreamWriter(dataStream);
					Endpoint.Serialize(writer);
					writer.Flush();
					return Convert.ToBase64String(dataStream.ToArray());
				} else {
					using (HashAlgorithm shaHash = createHashAlgorithm(store))
					using (CryptoStream shaStream = new CryptoStream(dataStream, shaHash, CryptoStreamMode.Write)) {
						StreamWriter writer = new StreamWriter(shaStream);
						Endpoint.Serialize(writer);
						if (persistNonce(Endpoint, store))
							writer.WriteLine(Nonce.Code);
						
						writer.Flush();
						shaStream.Flush();
						shaStream.FlushFinalBlock();

						byte[] hash = shaHash.Hash;
						byte[] data = new byte[1 + hash.Length + dataStream.Length];
						data[0] = 1; // there is a signature
						Buffer.BlockCopy(hash, 0, data, 1, hash.Length);
						Buffer.BlockCopy(dataStream.ToArray(), 0, data, 1 + hash.Length, (int)dataStream.Length);

						return Convert.ToBase64String(data);
					}
				}
			}
		}
Ejemplo n.º 17
0
        static void Decrypt(string[] args)
        {
            //Precheck if a tmp file already exists.
            //If so delete it.
            if (File.Exists(args[0] + ".tmp"))
            {
                Display("Destroying old .tmp files.");
                DestroyFile(args[0] + ".tmp");
                Display("Done.");
            }

            //SET UP STREAMS//
            FileStream Output;
            FileStream Input;
            CryptoStream CryptStream;

            //SET UP SERVICE PROVIDERS//
            AesCryptoServiceProvider ACSP = new AesCryptoServiceProvider();

            //AES PARAMETERS//
            ACSP.Padding = PaddingMode.PKCS7;
            Display("Creating keys.");
            ACSP.IV = GenerateIV(args[2]);      //initialization vector
            ACSP.Key = GenerateKey(args[2]);    //32 byte key
            Display("Done.");

            Input = new FileStream(args[0], FileMode.Open);
            Output = new FileStream(args[0] + ".tmp", FileMode.CreateNew);
            CryptStream = new CryptoStream(Input, ACSP.CreateDecryptor(), CryptoStreamMode.Read);

            Display("Starting decryption.");
            CryptStream.CopyTo(Output);
            Display("Done.");
            Input.Flush();
            Input.Dispose();
            CryptStream.Flush();
            //CryptStream.Dispose(); <-- Is disposed with input.
            Output.Flush();
            Output.Dispose();

            Display("Destroying old raw file.");
            DestroyFile(args[0]);
            Display("Done.");

            //Rename .tmp to the original file.
            Display("Renaming new file.");
            File.Move(args[0] + ".tmp", args[0]);
            Display("Done.");

            ACSP.Dispose();

            Display("Decryption process completed.");
            Console.ReadKey();
            return;
        }
Ejemplo n.º 18
0
 public string Decrypt(string data,int vi)
 {
     MemoryStream ms = new MemoryStream();
     Byte[] tb = Convert.FromBase64String(data);
     des.Key = Convert.FromBase64String(Keys[vi]);
     des.IV = Convert.FromBase64String(IVs[vi]);
     CryptoStream cs = new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);
     cs.Write(tb,0,tb.Length);
     cs.Flush();
     cs.Close();
     return Encoding.Unicode.GetString(ms.ToArray());
 }
Ejemplo n.º 19
0
 internal string Decrypt(string cipherText)
 {
     var keyBytes = new Rfc2898DeriveBytes(Password, salt, Iterations);
     var alg = new RijndaelManaged {Key = keyBytes.GetBytes(32), IV = keyBytes.GetBytes(16)};
     var decryptStream = new MemoryStream();
     var decrypt = new CryptoStream(decryptStream, alg.CreateDecryptor(), CryptoStreamMode.Write);
     byte[] data = Convert.FromBase64String(cipherText);
     decrypt.Write(data, 0, data.Length);
     decrypt.Flush();
     decrypt.Close();
     return Encoding.UTF8.GetString(decryptStream.ToArray());
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Permet de crypter une chaine de caractères
        /// </summary>
        /// <param name="p_chaineACrypter">Chaine de caractères qui doit être cryptée</param>
        /// <returns>
        /// La chaine de caractères cryptée
        /// </returns>
        public string Crypter(string p_chaineACrypter)
        {
            byte[] cleEnByte = new byte[32];
            MemoryStream memoryBuffer = new MemoryStream();

            CryptoStream crypteur = new CryptoStream(memoryBuffer, _rijndael.CreateEncryptor(_cleHasher, _vecteurInitialisation), CryptoStreamMode.Write);
            crypteur.Write(Encoding.ASCII.GetBytes(p_chaineACrypter), 0, p_chaineACrypter.Length);
            crypteur.Flush();
            crypteur.Close();

            return Convert.ToBase64String(memoryBuffer.ToArray());
        }
Ejemplo n.º 21
0
        public static string Decrypt(string base64Input)
        {
            if (string.IsNullOrEmpty(base64Input))
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(base64Input))
            {
                return string.Empty;
            }

            // Get inputs as bytes
            byte[] encryptBytes = Convert.FromBase64String(base64Input);
            byte[] saltBytes = Encoding.UTF8.GetBytes(SALT);

            // We're using the PBKDF2 standard for password-based key generation
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(
                PASS, saltBytes);

            // Our symmetric encryption algorithm
            AesManaged aes = new AesManaged();
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            aes.Key = rfc.GetBytes(aes.KeySize/8);
            aes.IV = rfc.GetBytes(aes.BlockSize/8);

            // Now, decryption
            ICryptoTransform decryptTrans = aes.CreateDecryptor();

            // Output stream, can be also a FileStream
            MemoryStream decryptStream = new MemoryStream();
            CryptoStream decryptor = new CryptoStream(
                decryptStream, decryptTrans, CryptoStreamMode.Write);
            decryptor.Write(encryptBytes, 0, encryptBytes.Length);
            decryptor.Flush();
            decryptor.Close();

            // Showing our decrypted content
            byte[] decryptBytes = decryptStream.ToArray();
            string decryptedString = Encoding.UTF8.GetString(
                decryptBytes, 0, decryptBytes.Length);

            // Close Stream
            decryptStream.Close();

            // Return decrypted text
            return decryptedString;
        }
Ejemplo n.º 22
0
 public static string EncryptString(string input, string password)
 {
     using (MemoryStream memoryStream = new MemoryStream())
     using (SymmetricAlgorithm algorithm = CreateRijndael(password, salt))
     {
         algorithm.IV = iv;
         using (CryptoStream cryptoStream = new CryptoStream(memoryStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
         {
             byte[] bytes = UTF32Encoding.Default.GetBytes(input);
             cryptoStream.Write(bytes, 0, bytes.Length);
             cryptoStream.Flush();
         }
         return Convert.ToBase64String(memoryStream.ToArray());
     }
 }
Ejemplo n.º 23
0
        public static string Encrypt(string input)
        {
            // Test data
            var data = input;
            var utfdata = Encoding.UTF8.GetBytes(data);
            var saltBytes = Encoding.UTF8.GetBytes("saltIsGoodForYou");

            // Our symmetric encryption algorithm
            using (var aes = new AesManaged())
            {
                // We're using the PBKDF2 standard for password-based key generation
#if !SILVERLIGHT
                using (var rfc = new Rfc2898DeriveBytes("thePassword", saltBytes))
                {
#else
                    var rfc = new Rfc2898DeriveBytes("thePassword", saltBytes);
#endif
                    // Setting our parameters
                    aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                    aes.KeySize = aes.LegalKeySizes[0].MaxSize;

                    aes.Key = rfc.GetBytes(aes.KeySize / 8);
                    aes.IV = rfc.GetBytes(aes.BlockSize / 8);

                    // Encryption
                    var encryptTransf = aes.CreateEncryptor();

                    // Output stream, can be also a FileStream
                    using (var encryptStream = new MemoryStream())
                    {
                        var encryptor = new CryptoStream(encryptStream, encryptTransf, CryptoStreamMode.Write);

                        encryptor.Write(utfdata, 0, utfdata.Length);
                        encryptor.Flush();
                        encryptor.Close();

                        // Showing our encrypted content
                        var encryptBytes = encryptStream.ToArray();

                        var encryptedString = Convert.ToBase64String(encryptBytes);

                        return encryptedString;
                    }
#if !SILVERLIGHT
                }
#endif
            }
        }
Ejemplo n.º 24
0
 // 加密
 private void button3_Click(object sender, EventArgs e)
 {
     try
     {
         if (pictureBox1.ImageLocation == null)
         { MessageBox.Show("请选择一幅图片用于加密"); return; }
         if (textBox1.Text == "")
         { MessageBox.Show("请选择加密文件路径"); return; }
         //图片流
         FileStream fsPic = new FileStream(pictureBox1.ImageLocation, FileMode.Open, FileAccess.Read);
         //加密文件流
         FileStream fsText = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
         //初始化Key IV
         byte[] bykey = new byte[16];
         byte[] byIv = new byte[8];
         fsPic.Read(bykey, 0, 16);
         fsPic.Read(byIv, 0, 8);
         //临时加密文件
         string strPath = textBox1.Text;//加密文件的路径
         int intLent = strPath.LastIndexOf("\\") + 1;
         int intLong = strPath.Length;
         string strName = strPath.Substring(intLent, intLong - intLent);//要加密的文件名称
         string strLinPath = "C:\\" + strName;//临时加密文件路径,所以被加密的文件不可以放在C盘的根目录下
         FileStream fsOut = File.Open(strLinPath, FileMode.Create, FileAccess.Write);
         //开始加密
         RC2CryptoServiceProvider desc = new RC2CryptoServiceProvider();//des进行加
         BinaryReader br = new BinaryReader(fsText);//从要加密的文件中读出文件内容
         CryptoStream cs = new CryptoStream(fsOut, desc.CreateEncryptor(bykey, byIv), CryptoStreamMode.Write);//写入临时加密文件
         cs.Write(br.ReadBytes((int)fsText.Length), 0, (int)fsText.Length);//写入加密流
         cs.FlushFinalBlock();
         cs.Flush();
         cs.Close();
         fsPic.Close();
         fsText.Close();
         fsOut.Close();
         File.Delete(textBox1.Text.TrimEnd());//册除原文件
         File.Copy(strLinPath, textBox1.Text);//复制加密文件
         File.Delete(strLinPath);//册除临时文件
         MessageBox.Show("加密成功");
         pictureBox1.ImageLocation = null;
         textBox1.Text = "";
     }
     catch (Exception ee)
     {
         MessageBox.Show(ee.Message);
     }
 }
Ejemplo n.º 25
0
        protected void BtnGenerate_Click(object sender, EventArgs e)
        {
            byte[] buf = GenerateRandom();

            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "inline; filename=\"random.txt\"");

            using (var stm = new CryptoStream(
                Response.OutputStream,
                new ToBase64Transform(),
                CryptoStreamMode.Write))
            {
                stm.Write(buf, 0, buf.Length);
                stm.Flush();
            }
            Response.End();
        }
 private static void Crypto(Stream input, Stream output, ICryptoTransform transform)
 {
     var buffer = new byte[512];
     var cs = new CryptoStream(output, transform, CryptoStreamMode.Write);
     for (long i = 0; i < input.Length; i += buffer.Length)
     {
         int sz = (int)Math.Min(input.Length - input.Position, buffer.Length);
         input.Read(buffer, 0, sz);
         cs.Write(buffer, 0, sz);
     }
     int pad = buffer.Length - (int)(input.Length % buffer.Length);
     if (pad > 0)
         cs.Write(new byte[pad], 0, pad);
     cs.Flush();
     output.Flush();
     output.Seek(0, SeekOrigin.Begin);
 }
Ejemplo n.º 27
0
        public static String Decrypt(String ciphertext, String salt)
        {
            Rfc2898DeriveBytes KeyBytes = new Rfc2898DeriveBytes(_privateKey, Encoding.UTF8.GetBytes(salt));
            //The deafault iteration count is 1000
            RijndaelManaged alg = new RijndaelManaged();
            alg.Key = KeyBytes.GetBytes(32);
            alg.IV = KeyBytes.GetBytes(16);
            MemoryStream decryptStream = new MemoryStream();
            //Stream to read
            CryptoStream decrypt = new CryptoStream(decryptStream, alg.CreateDecryptor(), CryptoStreamMode.Write);
            //convert  ciphertext to byte array
            byte[] data = Convert.FromBase64String(ciphertext); //IF using for WEB APPLICATION and getting ciphertext via Querystring change code to : Convert.FromBase64String(ciphertext.Replace(」 「,」+」));

            decrypt.Write(data, 0, data.Length); //data to encrypt,start,stop
            decrypt.Flush();
            decrypt.Close();
            return Encoding.UTF8.GetString(decryptStream.ToArray());//return PlainText
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Decrypt a Base64 string using Advanced Encryption Standard(AES) 256 bit symmetric encryption format
        /// and returns the decrypted string. The decryption key is generated based on the
        /// assembly public key.
        /// </summary>
        /// <param name="stringToDecrypt">Input String to decrypy in Base64 format.</param>
        /// <returns>Decrypted output string.</returns>
        public string DecryptString(string valueToDecrypt)
        {
            using (MemoryStream msDecrypted = new MemoryStream())
            {
                // Create a new instance of the RijndaelManaged
                // class.  This generates a new key and initialization
                // vector (IV).
                using (RijndaelManaged cryptoProvider = new RijndaelManaged())
                {
                    //A (128/192/256) bit key and 128 bit IV is required for this provider.
                    symKey = new byte[16];
                    symIV = new byte[16];

                    //Get the public key from the executing assembly,
                    //this will be based on the strong name associated with the dll/with which
                    //the project was build
                    byte[] publicKey = Assembly.GetExecutingAssembly().GetName().GetPublicKey();

                    Encoding encoding = Encoding.UTF8;
                    string keyValue = encoding.GetString(publicKey);
                    GenerateKeyVector(keyValue);

                    cryptoProvider.KeySize = 128;
                    cryptoProvider.Key = symKey;
                    cryptoProvider.IV = symIV;

                    // Create a decryptor to perform the stream transform.
                    using (ICryptoTransform cryptoTrans = cryptoProvider.CreateDecryptor())
                    {

                        //AES decryption transform on incoming bytes.
                        using (CryptoStream cryptoStreamDecr = new CryptoStream(msDecrypted, cryptoTrans, CryptoStreamMode.Write))
                        {

                            byte[] arrayInput = Convert.FromBase64String(valueToDecrypt);
                            cryptoStreamDecr.Write(arrayInput, 0, arrayInput.Length);
                            cryptoStreamDecr.Flush();
                        }
                    }
                    //Return decrypted string
                    return encoding.GetString(msDecrypted.ToArray());
                }
            }
        }
Ejemplo n.º 29
0
            public static string DecryptFile(string sInputFilename, string sKey)
            {
                string result = "";

                DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                //A 64 bit key and IV is required for this provider.
                //Set secret key For DES algorithm.
                DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                //Set initialization vector.
                DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

                //Create a file stream to read the encrypted file back.
                FileStream fsread = new FileStream(sInputFilename,
                   FileMode.Open,
                   FileAccess.Read);
                //Create a DES decryptor from the DES instance.
                ICryptoTransform desdecrypt = DES.CreateDecryptor();
                //Create crypto stream set to read and do a
                //DES decryption transform on incoming bytes.
                //CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
                //Print the contents of the decrypted file.

                /*StreamWriter fsDecrypted = new StreamWriter(outputFile);
                fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
                fsDecrypted.Flush();
                fsDecrypted.Close();*/

                using (var output = new MemoryStream())
                {
                    using (var cryptStream = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read))
                    {
                        var buffer = new byte[1024];
                        var read = cryptStream.Read(buffer, 0, buffer.Length);
                        while (read > 0)
                        {
                            output.Write(buffer, 0, read);
                            read = cryptStream.Read(buffer, 0, buffer.Length);
                        }
                        cryptStream.Flush();
                        result = Encoding.Unicode.GetString(output.ToArray());
                    }
                }
                return result;
            }
Ejemplo n.º 30
0
        public static string Encrypt(string plaintext)
        {
            byte[] rgbIV;
            byte[] key;

            RijndaelManaged rijndael = BuildRigndaelCommon(out rgbIV, out key);

            //convert plaintext into a byte array
            byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);

            byte[] cipherTextBytes = null;

            //create uninitialized Rijndael encryption obj
            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                //Call SymmetricAlgorithm.CreateEncryptor to create the Encryptor obj
                var transform = rijndael.CreateEncryptor();

                //Chaining mode
                symmetricKey.Mode = CipherMode.CFB;
                //create encryptor from the key and the IV value
                ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, rgbIV);

                //define memory stream to hold encrypted data
                using (var ms = new MemoryStream())
                using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    //encrypt contents of cryptostream
                    cs.Write(plaintextBytes, 0, plaintextBytes.Length);
                    cs.Flush();
                    cs.FlushFinalBlock();

                    //convert encrypted data from a memory stream into a byte array
                    ms.Position = 0;
                    cipherTextBytes = ms.ToArray();

                    ms.Close();
                    cs.Close();
                }
            }

            //store result as a hex value
            return BitConverter.ToString(cipherTextBytes).Replace("-", "");
        }