将数据流链接到加密转换的流CryptoStream 类

来源:互联网 发布:跳舞毯哪款最好 知乎 编辑:程序博客网 时间:2024/05/29 14:50
1.命名空间:System.Security.Cryptography
程序集:mscorlib(在 mscorlib.dll 中)

----------------------------------------------------
继承层次结构
-System.Object
----- System.MarshalByRefObject
--------- System.IO.Stream
-------------System.Security.Cryptography.CryptoStream
2.-------------------------------
        公共语言运行库使用面向流的设计进行加密。该设计的核心是 CryptoStream。实现 CryptoStream 的任何加密对象可以和实现 Stream 的任
何对象链接起来,因此一个对象的流式处理输出可以馈送到另一个对象的输入。不需要分别存储中间结果(第一个对象的输出)。
        通过调用 Close 方法完成 CryptoStream 对象的使用后,始终应该显式关闭该对象。这会刷新流并使所有剩余的数据块都被 CryptoStream
对象处理。但是,如果在调用 Close 方法前发生了异常,CryptoStream 对象可能会关闭。为确保 Close 方法始终被调用,请在 try/catch 语句的
finally 块中放置 Close 方法调用。
用目标数据流、要使用的转换和流的模式初始化 CryptoStream 类的新实例。
public CryptoStream (Stream stream,ICryptoTransform transform,
CryptoStreamMode mode)
参数:
stream-- 对其执行加密转换的流。
transform-- 要对流执行的加密转换。
mode--CryptoStreamMode 值之一。
 任何从 Stream 导出的对象都可以传入 stream 参数。任何实现 ICryptoTransform(例如 HashAlgorithm)的对象都可以传入transform 参数。
3.CryptoStream.Write 方法 
--------------------------------------
将一个字节序列写入当前 CryptoStream,并将流中的当前位置提升写入的字节数。
public override void Write (byte[ ] buffer, int offset, int count)
参数
buffer: 字节数组。此方法将 count 个字节从 buffer 复制到当前流。
offset:buffer 中的字节偏移量,从此偏移量开始将字节复制到当前流。
count:要写入当前流的字节数。
4.CryptoStream.FlushFinalBlock 方法 
----------------------------------------------------
用缓冲区的当前状态更新基础数据源或储存库,随后清除缓冲区。
public void FlushFinalBlock ()
5.--------------------------------
如:
   private string DecryptString(string Value)
  {
        ICryptoTransform transform1=this.mCSP.CreateDecrytor(this.mCSP.Key,this.mCSP.IV);
       byte [ ] buffer1=Convert.FromBase64String(Value);
       MemoryStream stream1=new MemoryStream();
       CryptoStream  stream2=new CryptoStream(stream1,transform1,CrytoStreamMode.Write);
      stream2.Write(buffer1,0,buffer1.Length);
      stream2.FlushFinalBlock();
      stream2.Close();
      return Encoding.UTF8.GetString(stream1.ToArray());
  }

NOTE:https://www.codeproject.com/articles/6465/using-cryptostream-in-c//加密,解密 例子
0 0
原创粉丝点击