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


C# CryptoStream类代码示例

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


CryptoStream类属于命名空间,在下文中一共展示了CryptoStream类的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: Decode

        /// <summary>
        /// 对数据进行解密
        /// </summary>
        /// <param name="decryptstring">需要解密的数据</param>
        /// <returns></returns>
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            try
            {
                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream(byEnc);
                CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cst);
                return sr.ReadToEnd();
            }
            catch
            {
                return null;
            }

        }
开发者ID:maanshancss,项目名称:ClassLibrary,代码行数:34,代码来源:1438759115$SoftDog.cs

示例3: Decrypt

    //cmThe function used to decrypt the text
    private static string Decrypt(string strText, string SaltKey)
    {
        byte[] byKey = { };
        byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
        byte[] inputByteArray = new byte[strText.Length + 1];

        try
        {
            byKey = System.Text.Encoding.UTF8.GetBytes(SaltKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(strText);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            return encoding.GetString(ms.ToArray());

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
开发者ID:Vinhbaba,项目名称:dskfeorfqlhvsea,代码行数:27,代码来源:Cipher.cs

示例4: 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

示例5: 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

示例6: Decrypt

    public static string Decrypt(byte[] key, byte[] iv, byte[] input)
    {
        if (key == null || iv == null || input == null)
        {
            return null;
        }

        // Create a memory stream to the passed buffer.
        MemoryStream ms = new MemoryStream(input);

        // Create a CryptoStream using the memory stream and the
        // CSP DES key.
        CryptoStream encStream = new CryptoStream(ms, m_desKey.CreateDecryptor(key, iv), CryptoStreamMode.Read);

        // Create a StreamReader for reading the stream.
        StreamReader sr = new StreamReader(encStream);

        // Read the stream as a string.
        string val = sr.ReadToEnd();

        // Close the streams.
        sr.Close();
        encStream.Close();
        ms.Close();

        return val;
    }
开发者ID:huyanoperation,项目名称:Scut,代码行数:27,代码来源:DES.cs

示例7: DecryptFile

 /// <summary>
 /// 对文件内容进行DES解密
 /// </summary>
 /// <param name="sourceFile">待解密的文件绝对路径</param>
 /// <param name="destFile">解密后的文件保存的绝对路径</param>
 public static void DecryptFile(string sourceFile, string destFile)
 {
     if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在!", sourceFile);
     byte[] btKey = Encoding.Default.GetBytes(key);
     byte[] btIV = Encoding.Default.GetBytes(iv);
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     byte[] btFile = File.ReadAllBytes(sourceFile);
     using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
     {
         try
         {
             using (CryptoStream cs = new CryptoStream(fs, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
             {
                 cs.Write(btFile, 0, btFile.Length);
                 cs.FlushFinalBlock();
             }
         }
         catch
         {
             throw;
         }
         finally
         {
             fs.Close();
         }
     }
 }
开发者ID:RushHang,项目名称:H_DataAssembly,代码行数:32,代码来源:DES.cs

示例8: 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

示例9: 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

示例10: Encrypt

    public static string Encrypt(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 encryptionStream = new MemoryStream())
                {
                    using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] cleanText = Encoding.UTF8.GetBytes(text);
                        encrypt.Write(cleanText, 0, cleanText.Length);
                        encrypt.FlushFinalBlock();
                    }

                    byte[] encryptedData = encryptionStream.ToArray();
                    string encryptedText = Convert.ToBase64String(encryptedData);


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

示例11: 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

示例12: Decrypt

 /// <summary>
 /// Return stream to read encrypted file.
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static CryptoStream Decrypt(string path)
 {
     FileStream encryptReader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Delete);
     var returnStream = new CryptoStream(encryptReader, RMCrypto.CreateDecryptor(Key, IV), CryptoStreamMode.Read);
     Debug.Log("Return encrypt stream");
     return returnStream;
 }
开发者ID:wuxin0602,项目名称:Nothing,代码行数:12,代码来源:EncriptionManagement.cs

示例13: Encrypt

 /// <summary>
 /// Return stream to write file in encrypted way.
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static CryptoStream Encrypt(string path)
 {
     FileStream encryptWriter = new FileStream(path, FileMode.Append,FileAccess.Write,FileShare.Delete);
     var returnStream = new CryptoStream(encryptWriter, RMCrypto.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
     Debug.Log("Return encrypt stream");
     return returnStream;
 }
开发者ID:wuxin0602,项目名称:Nothing,代码行数:12,代码来源:EncriptionManagement.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类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。