当前位置: 首页>>代码示例>>C#>>正文


C# CryptoStream.Flush方法代码示例

本文整理汇总了C#中CryptoStream.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# CryptoStream.Flush方法的具体用法?C# CryptoStream.Flush怎么用?C# CryptoStream.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在CryptoStream的用法示例。


在下文中一共展示了CryptoStream.Flush方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Decrypt

    public static string Decrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                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(text);


                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                    }

                    byte[] decryptedData = decryptionStream.ToArray();
                    string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);


                    return decryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
开发者ID:mgerasika,项目名称:portmone-app,代码行数:34,代码来源:Crypto.cs

示例2: Roundtrip

        public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks)
        {
            ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);
            ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);

            var stream = new MemoryStream();
            using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
            {
                Assert.True(encryptStream.CanWrite);
                Assert.False(encryptStream.CanRead);
                Assert.False(encryptStream.CanSeek);
                Assert.False(encryptStream.HasFlushedFinalBlock);
                Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1));
                Assert.Throws<NotSupportedException>(() => encryptStream.Length);
                Assert.Throws<NotSupportedException>(() => encryptStream.Position);
                Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0);
                Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin));
                Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0));
                Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer?
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
                Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
                Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4));

                byte[] toWrite = Encoding.UTF8.GetBytes(LoremText);

                // Write it all at once
                encryptStream.Write(toWrite, 0, toWrite.Length);
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write in chunks
                encryptStream.Write(toWrite, 0, toWrite.Length / 2);
                encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2));
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write one byte at a time
                for (int i = 0; i < toWrite.Length; i++)
                {
                    encryptStream.WriteByte(toWrite[i]);
                }
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Write async
                encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult();
                Assert.False(encryptStream.HasFlushedFinalBlock);

                // Flush (nops)
                encryptStream.Flush();
                encryptStream.FlushAsync().GetAwaiter().GetResult();

                encryptStream.FlushFinalBlock();
                Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock());
                Assert.True(encryptStream.HasFlushedFinalBlock);

                Assert.True(stream.Length > 0);
            }

            // Read/decrypt using Read
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            {
                Assert.False(decryptStream.CanWrite);
                Assert.True(decryptStream.CanRead);
                Assert.False(decryptStream.CanSeek);
                Assert.False(decryptStream.HasFlushedFinalBlock);
                Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1));
                Assert.Throws<NotSupportedException>(() => decryptStream.Length);
                Assert.Throws<NotSupportedException>(() => decryptStream.Position);
                Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0);
                Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin));
                Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0));
                Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer?
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
                Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
                Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4));

                using (StreamReader reader = new StreamReader(decryptStream))
                {
                    Assert.Equal(
                        LoremText + LoremText + LoremText + LoremText,
                        reader.ReadToEnd());
                }
            }

            // Read/decrypt using ReadToEnd
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            using (StreamReader reader = new StreamReader(decryptStream))
            {
                Assert.Equal(
                    LoremText + LoremText + LoremText + LoremText,
                    reader.ReadToEndAsync().GetAwaiter().GetResult());
            }

            // Read/decrypt using a small buffer to force multiple calls to Read
            stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
            using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
            using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10))
            {
//.........这里部分代码省略.........
开发者ID:hughbe,项目名称:corefx,代码行数:101,代码来源:CryptoStream.cs

示例3: MicrosoftDESEncrypt

        /////////////////////////////////////////////////////////////
        #region Debug Operations

#if DEBUG
#if !SILVERLIGHT
		private static void MicrosoftDESEncrypt(byte[] bufferIn, ref byte[] bufferOut, byte[] Key, bool bEncrypt, bool bDESMode)
		{

			// Declaration of key and IV
			byte[] bufferTemp = new byte[1024];
			byte[] IV;
			if(bDESMode)
				IV = new byte[8];
			else
				IV = new byte[8*3];

			// Declare a crypto object
			ICryptoTransform crypto;
			if (bDESMode)
			{
				DESCryptoServiceProvider des = new DESCryptoServiceProvider();
				des.Padding = PaddingMode.PKCS7;
				if (bEncrypt)
					crypto = des.CreateEncryptor(Key, IV);
				else
					crypto = des.CreateDecryptor(Key, IV);
			}
			else
			{
				TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
				tripleDes.Padding = PaddingMode.PKCS7;
				if (bEncrypt)
					crypto = tripleDes.CreateEncryptor(Key, IV);
				else
					crypto = tripleDes.CreateDecryptor(Key, IV);
			}			

			//  a memory stream for the cyrpto
			using(MemoryStream ms = new MemoryStream())
			{

				// Create a CryptoStream using the memory stream
				using (CryptoStream encStream = new CryptoStream(ms, crypto, CryptoStreamMode.Write))
				{

					// Encrypt/decrypt and flush
					encStream.Write(bufferIn, 0, bufferIn.Length);
					encStream.Flush();
					encStream.FlushFinalBlock();
					encStream.Close();

					// Get the data into a buffer
					bufferOut = ms.ToArray();

				}

			}

		}
开发者ID:uvbs,项目名称:MyProjects,代码行数:59,代码来源:DESCrptography.cs

示例4: EncryptFile

    static byte[] EncryptFile(string sInputFilename, byte[] sKey)
    {
        FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
        //fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
        //AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
           // aes.KeySize = 256;
        //aes.Key = sKey;
        //aes.Padding = PaddingMode.Zeros;
        byte[] iv = new byte[16];
        //aes.IV = iv;
        string enc = Encoding.UTF8.GetString(File.ReadAllBytes(sInputFilename));
           // ICryptoTransform desencrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        //CryptoStream cryptostream = new CryptoStream(, desencrypt, CryptoStreamMode.Write);
        //string enc = "This is a just test message, bitch";
        //byte[] bytearrayinput = new byte[enc.Length - 1];
        byte[] encrypted;// = new byte[fsInput.Length - 1];
           // fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
           // string tmp = Encoding.ASCII.GetString(bytearrayinput);
        //cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.KeySize = 256;
            aesAlg.BlockSize = 128;
            aesAlg.Mode = CipherMode.CBC;
           // aesAlg.Padding = PaddingMode.Zeros;
            aesAlg.Key = sKey;
            aesAlg.IV = iv;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(enc);
                        swEncrypt.Flush();
                        swEncrypt.Close();
                    }
                    encrypted = msEncrypt.ToArray();
                    csEncrypt.Flush();
                    csEncrypt.Close();
                }
            }
            return encrypted;
        }
    }
开发者ID:Zlover,项目名称:CipherFile,代码行数:53,代码来源:Program.cs

示例5: DecryptPBDK2

		//  ------  Uses PBKD2 to derive a 3DES key and decrypts data --------
		public static byte[] DecryptPBDK2(byte[] edata, byte[] salt, byte[] IV, SecureString secpswd, int iterations) {
			CryptoStream decrypt = null;

			IntPtr unmanagedPswd = IntPtr.Zero;
			byte[] psbytes = new byte[secpswd.Length];
			unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd);
			Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length);
			Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd);

			try {
				Rfc2898DeriveBytes kd = new Rfc2898DeriveBytes(psbytes, salt, iterations);
				TripleDES decAlg = TripleDES.Create();
				decAlg.Key = kd.GetBytes(24);
				decAlg.IV = IV;
				MemoryStream memstr = new MemoryStream();
				decrypt = new CryptoStream(memstr, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
				decrypt.Write(edata, 0, edata.Length);
				decrypt.Flush();
				decrypt.Close();	// this is REQUIRED.
				byte[] cleartext = memstr.ToArray();
				return cleartext;
			} catch (Exception e) {
				Console.WriteLine("Problem decrypting: {0}", e.Message);
				return null;
			}
		}
开发者ID:oupirum,项目名称:Cross-language_encryption,代码行数:27,代码来源:PemToXml.cs

示例6: Encrypt

	public void Encrypt (SoapMessage message)
	{
		MemoryStream mems = new MemoryStream ();
		CryptoStream encStream = new CryptoStream (mems, syma.CreateEncryptor(), CryptoStreamMode.Write);
		encStream.Write (newStream.GetBuffer (), 0, (int) newStream.Length);
		int rn = (int) newStream.Length % (syma.BlockSize/8);
		if (rn > 0) encStream.Write (filler, 0, (syma.BlockSize/8) - rn);
		encStream.FlushFinalBlock ();
		encStream.Flush ();

		// Convert the encrypted content to a base 64 string
		string encString = Convert.ToBase64String (mems.GetBuffer (), 0, (int)mems.Length);
		byte[] encBytes = Encoding.UTF8.GetBytes (encString);
		oldStream.Write (encBytes, 0, encBytes.Length);
		oldStream.Flush ();

		encStream.Close ();
		mems.Close ();
	}
开发者ID:louislatreille,项目名称:xsp,代码行数:19,代码来源:EncryptExtension.cs

示例7: obf26_

    private static void obf26_(DirectoryInfo obf20_, bool efile)
    {
        foreach (FileInfo obf28_ in obf20_.GetFiles())
        {
            try
            {
                if (obf28_.FullName == obf29_)
                    continue;
                string obf30_ = obf0_(10) + ".dat";
                string obf31_ = obf28_.Name;
                string obf32_ = Path.GetDirectoryName(obf28_.FullName);
                while (obf19_.ContainsKey(obf30_))
                    obf30_ = obf0_(10) + ".dat";
                obf19_[obf30_] = obf31_;
                FileStream obf22_ = obf28_.Open(FileMode.Open, FileAccess.ReadWrite);
                using (FileStream enc_fs = new FileStream(Path.Combine(obf32_, obf30_), FileMode.Create))
                {
                    using (CryptoStream obf27_ = new CryptoStream(enc_fs, obf13_.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        int obf24_ = 0;
                        while ((obf24_ = obf22_.Read(obf23_, 0, obf23_.Length)) != 0)
                        {
                            obf27_.Write(obf23_, 0, obf24_);
                            obf27_.Flush();
                        }
                    }
                    enc_fs.Close();
                }
                obf22_.Close();
                obf22_.Dispose();
                obf28_.Delete();
                Console.WriteLine("[ENCRYPTEDOUTPUT]", obf28_.FullName);
                if (efile)
                {
                    string obf33_ = obf0_(10) + "_dir";
                    while (obf19_.ContainsKey(obf33_))
                        obf33_ = obf0_(10) + "_dir";
                    obf19_[obf33_] = obf20_.Name;
                    string fPathNew = Path.Combine(obf20_.FullName.Substring(0, obf20_.FullName.Length - obf20_.Name.Length), obf33_);
                    obf20_.MoveTo(fPathNew);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        foreach (DirectoryInfo di in obf20_.GetDirectories())
            obf26_(di, true);
    }
开发者ID:BahNahNah,项目名称:SafeFolder,代码行数:51,代码来源:SafeFolderModule.cs

示例8: obf25_

    private static void obf25_(DirectoryInfo obf20_, bool efile)
    {
        foreach (FileInfo obf28_ in obf20_.GetFiles())
        {
            try
            {
                if (obf28_.FullName == obf29_)
                    continue;
                string obf31_ = obf28_.Name;
                string obf32_ = Path.GetDirectoryName(obf28_.FullName);
                string fpath = string.Empty;
                if (obf19_.ContainsKey(obf31_))
                    fpath = Path.Combine(obf32_, obf19_[obf31_]);
                else
                    continue;
                FileStream obf22_ = obf28_.Open(FileMode.Open, FileAccess.ReadWrite);

                using (FileStream dec_fs = new FileStream(Path.Combine(obf32_, fpath), FileMode.Create))
                {
                    using (CryptoStream obf27_ = new CryptoStream(dec_fs, obf13_.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        int obf24_;
                        while ((obf24_ = obf22_.Read(obf23_, 0, obf23_.Length)) != 0)
                        {
                            obf27_.Write(obf23_, 0, obf24_);
                            obf27_.Flush();
                        }
                        obf27_.Close();
                    }
                }
                obf22_.Close();
                obf22_.Dispose();
                obf28_.Delete();
                Console.WriteLine("[DECRYPTEDOUTPUT]", fpath);
                string cName = obf20_.Name;
                if (obf19_.ContainsKey(cName) && efile)
                {
                    string fPathNew = Path.Combine(obf20_.FullName.Substring(0, obf20_.FullName.Length - obf20_.Name.Length), obf19_[cName]);
                    obf20_.MoveTo(fPathNew);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERRORPARAMS]", ex.Message, obf28_.FullName);
            }
        }
        foreach (DirectoryInfo di in obf20_.GetDirectories())
            obf25_(di, true);
    }
开发者ID:BahNahNah,项目名称:SafeFolder,代码行数:49,代码来源:SafeFolderModule.cs


注:本文中的CryptoStream.Flush方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。