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


C# CryptoStream.Close方法代码示例

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


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

示例1: TestKnownEnc

    static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
 		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        cs.FlushFinalBlock();
        CipherCalculated = ms.ToArray();
        cs.Close();

		Console.WriteLine("Computed this cyphertext:");
        PrintByteArray(CipherCalculated);
        

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:34,代码来源:AESKnownEnc2.cs

示例2: Decrypt

 /// <summary>
 /// Decrypts a Base64 encoded string previously generated with a specific crypt class, returns a string
 /// </summary>
 /// <param name="cipherText">A base64 encoded string containing encryption information</param>
 /// <param name="passPhrase">The passphrase used to encrypt the inputed text</param>
 /// <returns></returns>
 public string Decrypt(string cipherText, string passPhrase)
 {
     try
         {
             var ciphertextS = DecodeFrom64(cipherText);
             var ciphersplit = Regex.Split(ciphertextS, "-");
             var passsalt = Convert.FromBase64String(ciphersplit[1]);
             var initVectorBytes = Convert.FromBase64String(ciphersplit[0]);
             var cipherTextBytes = Convert.FromBase64String(ciphersplit[2]);
             var password = new PasswordDeriveBytes(passPhrase, passsalt, "SHA512", 100);
             var keyBytes = password.GetBytes(256/8);
             var symmetricKey = new RijndaelManaged();
             symmetricKey.Mode = CipherMode.CBC;
             var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
             var memoryStream = new MemoryStream(cipherTextBytes);
             var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
             var plainTextBytes = new byte[cipherTextBytes.Length];
             var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
             memoryStream.Close();
             cryptoStream.Close();
             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
         }
         catch (Exception m)
         {
             return "error";
         }
 }
开发者ID:BinaryEvolved,项目名称:C-AES256-Encryption-Class,代码行数:33,代码来源:Crypt.cs

示例3: AES_Decrypt

    private static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
    {
        byte[] decryptedBytes = null;

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                try
                {
                    AES.KeySize = AESKeySize_256;
                    AES.Key = passwordBytes;
                    AES.Mode = AESCipherMode_ECB;
                    AES.Padding = AESPadding_PKCS7;

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

        return decryptedBytes;
    }
开发者ID:neiltuma,项目名称:steve_prj,代码行数:31,代码来源:testSSO.aspx.cs

示例4: Decrypt

 public static string Decrypt(string stringToDecrypt)
 {
     string sEncryptionKey = "thuynnxkey";
     byte[] key = { };
     byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
     byte[] inputByteArray = new byte[stringToDecrypt.Length];
     try
     {
         key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         inputByteArray = Convert.FromBase64String(stringToDecrypt);
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         cs.Close();
         Encoding encoding = Encoding.UTF8;
         return encoding.GetString(ms.ToArray());
     }
     catch (System.Exception ex)
     {
         SiAuto.Main.LogString("Lỗi :", ex.ToString());
         return (string.Empty);
     }
 }
开发者ID:trantrung2608,项目名称:ilinkbay,代码行数:25,代码来源:Utils.cs

示例5: Encrypt

    /// <summary>
    /// Encrypt string using AES 128
    /// </summary>
    /// <param name="plaintext"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string Encrypt(string plaintext, string key)
    {
        byte[] keybytes = Encoding.UTF8.GetBytes(key);

        RijndaelManaged aes = new RijndaelManaged();
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.None;
        byte[] IVbytes = Encoding.ASCII.GetBytes("dongbinhuiasxiny");

        ICryptoTransform encryptor = aes.CreateEncryptor(keybytes, IVbytes);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

        byte[] plainBytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(plaintext)));

        cs.Write(plainBytes, 0, plainBytes.Length);

        cs.FlushFinalBlock();

        byte[] cipherBytes = ms.ToArray();

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

        return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
    }
开发者ID:masterjay,项目名称:BankofTaiwanActive,代码行数:32,代码来源:libAES.cs

示例6: AES_Encrypt

    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        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 (RijndaelManaged AES = new RijndaelManaged())
          {
        AES.KeySize = 256;
        AES.BlockSize = 128;

        var key = new Rfc2898DeriveBytes(passwordBytes, 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;
        //end public byte[] AES_Encrypt
    }
开发者ID:JorgMU,项目名称:AES256,代码行数:33,代码来源:SimpleAES256.cs

示例7: DeCryption

    private string DeCryption(string content, string sKey, string sIV)
    {
        try
        {
            byte[] inputByteArray = Convert.FromBase64String(content);
            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                //byte[] inputByteArray = Convert.FromBase64String(content);
                desProvider.Key = System.Text.Encoding.ASCII.GetBytes(sKey);
                desProvider.IV = System.Text.Encoding.ASCII.GetBytes(sIV);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms,desProvider.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    //cs.Clear();
                    cs.Write(inputByteArray,0,inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }

                string str = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        catch
        {
            return "String Not Base64 Encode!!!";
        }
    }
开发者ID:IanWendy,项目名称:IanTools,代码行数:29,代码来源:CryptionManager.cs

示例8: Load

	public static SaveData Load()
	{
		if (!File.Exists("save01.sav"))
			return null;
			
		SaveData data = null;
		using(Stream stream = File.Open("save01.sav", FileMode.Open)) {
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			binaryFormatter.Binder = new VersionDeserializationBinder(); 
			
			byte[] byKey = Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
			using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) {
				using (Stream cryptoStream = new CryptoStream(stream, des.CreateDecryptor(byKey, dv), CryptoStreamMode.Read))
				{
					Log.debug("Save", "Loading...");
					try {
						data = (SaveData) binaryFormatter.Deserialize(cryptoStream);
					} catch (Exception e) {
						Log.debug("Save", ""+e);
						return new SaveData();
					}
					Log.debug("Save", "Loaded (level={0})", data.level);
					cryptoStream.Close();
				}
			}
			stream.Close();
		}
		return data;
	}
开发者ID:Niklas83,项目名称:UnityGame1,代码行数:29,代码来源:SaveData.cs

示例9: Main

	static int Main ()
	{
		string filename = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"encrypt.tmp");
		string data = "this is sensitive data";

		DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
		des.GenerateIV ();
		des.GenerateKey ();

		// -----------  WRITING ENCRYPTED SERIALIZED DATA ------------------
		Stream stream = new FileStream (filename, FileMode.Create, FileAccess.Write);
		stream = new CryptoStream (stream, des.CreateEncryptor (), CryptoStreamMode.Write);
		BinaryFormatter bformatter = new BinaryFormatter ();
		bformatter.Serialize (stream, data);
		stream.Close ();

		stream = null;
		bformatter = null;
		data = string.Empty;

		// -----------  READING ENCRYPTED SERIALIZED DATA ------------------
		stream = new FileStream (filename, FileMode.Open, FileAccess.Read);
		stream = new CryptoStream (stream, des.CreateDecryptor (), CryptoStreamMode.Read);
		bformatter = new BinaryFormatter ();
		data = (string) bformatter.Deserialize (stream);
		stream.Close ();

		//----------- CHECK RESULTS ----------------
		if (data != "this is sensitive data")
			return 1;

		return 0;
	}
开发者ID:mono,项目名称:gert,代码行数:34,代码来源:test.cs

示例10: Test

    public static Boolean Test() {
    	String Text = "This is some test text";
    	
    	Console.WriteLine("Original text : "  + Text);
    	
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write);
		cs.Write(Encoding.ASCII.GetBytes(Text), 0, Text.Length);
		cs.Close();
		
    	Console.WriteLine("Encoded : " + Encoding.ASCII.GetString(ms.ToArray()));

        MemoryStream ms1 = new MemoryStream();
        CryptoStream cs1 = new CryptoStream(ms1, new FromBase64Transform(), CryptoStreamMode.Write);
		cs1.Write(ms.ToArray(), 0, (int)ms.ToArray().Length);
		cs1.Close();
    		
    	Console.WriteLine("Decoded : " + Encoding.ASCII.GetString(ms1.ToArray()));

    	String mod = Encoding.ASCII.GetString((Byte[])ms.ToArray().Clone());
    	mod = mod.Insert(17, "\n").Insert(4, "  ").Insert(8,"\t");
    	Byte[] modified = Encoding.ASCII.GetBytes(mod);
    	
        MemoryStream ms2 = new MemoryStream();
        CryptoStream cs2 = new CryptoStream(ms2, new FromBase64Transform(), CryptoStreamMode.Write);
		cs2.Write(modified, 0, (int)modified.Length);
		cs2.Close();

    	Console.WriteLine("Decoded (with whitespaces) : " + Encoding.ASCII.GetString(ms2.ToArray()));
    	
    	if (!Compare(ms1.ToArray(), ms2.ToArray())) return false;
 
        return true;
    }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:34,代码来源:TestBase64.cs

示例11: DecryptString

 protected string DecryptString(string InputText, string Password)
 {
     try
     {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();
         byte[] EncryptedData = Convert.FromBase64String(InputText);
         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
         // Create a decryptor from the existing SecretKey bytes.
         ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
         MemoryStream memoryStream = new MemoryStream(EncryptedData);
         // Create a CryptoStream. (always use Read mode for decryption).
         CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
         // Since at this point we don't know what the size of decrypted data
         // will be, allocate the buffer long enough to hold EncryptedData;
         // DecryptedData is never longer than EncryptedData.
         byte[] PlainText = new byte[EncryptedData.Length];
         // Start decrypting.
         int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
         memoryStream.Close();
         cryptoStream.Close();
         // Convert decrypted data into a string.
         string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
         // Return decrypted string.
         return DecryptedData;
     }
     catch (Exception exception)
     {
         return (exception.Message);
     }
 }
开发者ID:DawnShift,项目名称:Multi-cloud-Encryption-,代码行数:31,代码来源:Cryptography.cs

示例12: DecryptString

	public static string DecryptString(string input, string cryptographicProvider_PublicKey, string cryptographicProvider_IV)
	{
		try
		{
			input = input.Replace(CryptographicProviderKey, String.Empty);

			using (var dataString = new MemoryStream())
			{
				var service = new TripleDESCryptoServiceProvider().CreateDecryptor(Encoding.UTF8.GetBytes(cryptographicProvider_PublicKey),
				 Encoding.UTF8.GetBytes(cryptographicProvider_IV));
				using (var cryptoStream = new CryptoStream(dataString, service, CryptoStreamMode.Write))
				{
					var inputData = Convert.FromBase64String(input);
					cryptoStream.Write(inputData, 0, inputData.Length);
					cryptoStream.FlushFinalBlock();

					var dataResult = dataString.ToArray();
					var resultString = Encoding.UTF8.GetString(Convert.FromBase64String(Convert.ToBase64String(dataResult)));
					cryptoStream.Close();

					return resultString;

				}
			}

		}
		catch (Exception e)
		{
			return e.ToString();
		}

	}
开发者ID:evkap,项目名称:DVS,代码行数:32,代码来源:DecryptField.cs

示例13: Main

    public static void Main() {
        string PlainText = "Titan";
        byte[] PlainBytes = new byte[5];
        PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray());
        PrintByteArray(PlainBytes);
        byte[] CipherBytes = new byte[8];
        PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null);
        byte[] IV = new byte[8];
        byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV);
        PrintByteArray(Key);
        PrintByteArray(IV);

        // Now use the data to encrypt something
        RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
        Console.WriteLine(rc2.Padding);
        Console.WriteLine(rc2.Mode);
        ICryptoTransform sse = rc2.CreateEncryptor(Key, IV);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs1.Write(PlainBytes, 0, PlainBytes.Length);
        cs1.FlushFinalBlock();
        CipherBytes = ms.ToArray();
        cs1.Close();
        Console.WriteLine(Encoding.ASCII.GetString(CipherBytes));
        PrintByteArray(CipherBytes);

        ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV);
        CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read);
        byte[] InitialText = new byte[5];
        cs2.Read(InitialText, 0, 5);
        Console.WriteLine(Encoding.ASCII.GetString(InitialText));
    	PrintByteArray(InitialText);
    }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:33,代码来源:DeriveBytesTest.cs

示例14: Encrypt

    //This method is to encrypt the password given by user.
    public static string Encrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        // setup the encryption algorithm
        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8);
        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);

        // encrypt the data
        byte[] rawData = Encoding.Unicode.GetBytes(data);
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateEncryptor(), CryptoStreamMode.Write))
        {
            memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length);
            cryptoStream.Write(rawData, 0, rawData.Length);
            cryptoStream.Close();

            byte[] encrypted = memoryStream.ToArray();
            return Convert.ToBase64String(encrypted);
        }
    }
开发者ID:progressiveinfotech,项目名称:PRO_FY13_40_Helpdesk-Support-and-Customization_TerexBest,代码行数:29,代码来源:Activate.aspx.cs

示例15: EncryptData

	private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
	     //Create the file streams to handle the input and output files.
	     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
	     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
	     fout.SetLength(0);

	     //Create variables to help with read and write.
	     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
	     long rdlen = 0;              //This is the total number of bytes written.
	     long totlen = fin.Length;    //This is the total length of the input file.
	     int len;                     //This is the number of bytes to be written at a time.

	     SymmetricAlgorithm des = new DESCryptoServiceProvider();
         des.Padding = PaddingMode.PKCS7;
	     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

	     Console.WriteLine("Encrypting...");

	     //Read from the input file, then encrypt and write to the output file.
	     while(rdlen < totlen)
	     {
	         len = fin.Read(bin, 0, 100);
	         encStream.Write(bin, 0, len);
	         rdlen = rdlen + len;
             Console.WriteLine("{0} bytes processed", rdlen);
         }
	     encStream.Close();
    }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:29,代码来源:EncDecFileScn.cs


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