加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用HashAlgorithm.TransformBlock / TransformFinalB

发布时间:2020-12-16 01:27:08 所属栏目:百科 来源:网络整理
导读:我想使用TransformBlock()/ TransformFinalBlock()在几个步骤中计算SHA1哈希: byte[] block1 = Encoding.ASCII.GetBytes("This");byte[] block2 = Encoding.ASCII.GetBytes("is");byte[] block3 = Encoding.ASCII.GetBytes("Sparta");SHA1 sha = new SHA1Ma
我想使用TransformBlock()/ TransformFinalBlock()在几个步骤中计算SHA1哈希:

byte[] block1 = Encoding.ASCII.GetBytes("This");
byte[] block2 = Encoding.ASCII.GetBytes("is");
byte[] block3 = Encoding.ASCII.GetBytes("Sparta");

SHA1 sha = new SHA1Managed();
sha.TransformBlock(block1,block1.Length,block1,0);
sha.TransformBlock(block2,block2.Length,block2,0);
sha.TransformFinalBlock(block3,block3.Length);

byte[] result = sha.Hash;

我知道还有其他方法来计算SHA1(例如:HashAlgorithm.ComputeHash()或CryptoStream).以上是更复杂代码的简化版本.

对我来说完全不清楚的是为outputBuffer数组传递什么(TransformBlock方法的第四个参数):

int TransformBlock(byte[] inputBuffer,int inputOffset,int inputCount,byte[] outputBuffer,int outputOffset);

MSDN page说:

Computes the hash value for the specified region of the input byte
array and copies the specified region of the input byte array to the
specified region of the output byte array

如果我不需要该阵列副本怎么办?我应该通过null吗? (为了避免每次都复制输入数组?)

这有什么典型的用途吗?

同样,似乎TransformFinalBlock()也将输入数组复制到输出数组. AFAIKm这是方法返回的内容:

byte[] TransformFinalBlock(byte[] inputBuffer,int inputCount);

解决方法

您链接的页面和示例非常清楚:

Calling the TransformBlock method with different input and output arrays results in an IOException.

甚至在使用上的例子很清楚:

offset += sha.TransformBlock(input,offset,size,input,offset);

SHA1实际上不需要该参数.但它是具有此签名的接口ICryptoTransform的实现.所以SHA1.TransformBlock()有那个(无用的)参数.请注意,您可以将输出设置为null(未记录但有效).

请注意,在HashAlgorithm(实现ICryptoTransform的SHA1的基类)中,TransformBlock内部有一个line,如:

if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset)))
    Buffer.BlockCopy(inputBuffer,inputOffset,outputBuffer,outputOffset,inputCount);

因此,如果将其设置为null或输入== output,则不会复制任何内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读