sha256:如何使用算法作为输入



好的,这是我的问题。我知道如何使用C#进行哈希,我制作了这个函数来哈希文件并提供进度条:

public String SHA384CheckSum(String pstrFilePath)
{
const Int32 BUFFER_MAX_SIZE = (4 * 1024 * 1000);  //4Mo
String strRetValue = "";
String strBaseCaption = this.Text;
Int64 dblProgression1;
Int64 dblProgression2 = 0;
this.Text = strBaseCaption + " [0%]";
//Should check if file exist first
if (AppEx.FileExist64(pstrFilePath) == true)
{
//using (SHA384 objSHA = SHA384.Create())
using (SHA384 objSHA = SHA384.Create()) {
using (FileStream objFileStream = new FileStream(pstrFilePath, FileMode.Open, FileAccess.Read))
{
Int32 _bufferSize;
Byte[] readAheadBuffer;
Int32 readAheadBytesRead;
Int64 lngBytesRemaining = objFileStream.Length;
Double dblTotalBytes = lngBytesRemaining;
while ((lngBytesRemaining > 0) && (this.glngState != 2))
{
if (lngBytesRemaining > BUFFER_MAX_SIZE)
{
_bufferSize = BUFFER_MAX_SIZE;
} else {
_bufferSize = (Int32)lngBytesRemaining;
}
readAheadBuffer = new Byte[_bufferSize];
readAheadBytesRead = objFileStream.Read(readAheadBuffer, 0, _bufferSize);
lngBytesRemaining = (lngBytesRemaining - _bufferSize);
if (lngBytesRemaining != 0)
{
objSHA.TransformBlock(readAheadBuffer, 0, readAheadBytesRead, readAheadBuffer, 0);
} else {
objSHA.TransformFinalBlock(readAheadBuffer, 0, readAheadBytesRead);
strRetValue = BitConverter.ToString(objSHA.Hash).Replace("-", "").ToLower();
}
dblProgression1 = (Int64)(((dblTotalBytes - lngBytesRemaining) / dblTotalBytes) * 100);
if (dblProgression1 != dblProgression2)
{
dblProgression2 = dblProgression1;
this.Text = strBaseCaption + " [" + dblProgression2.ToString() + "%]";
Application.DoEvents();
}
}
}
}
}
this.Text = strBaseCaption + " [100%]";
return strRetValue;
}

这工作做得很好。现在让我们假设我想使用Sha256进行散列。我所要做的就是更改这条线:

using (SHA384 objSHA = SHA384.Create())
to
using (SHA256 objSHA = SHA256.Create())

How can I pass this as a parameter to the function so I could:
SHA256 objSHA;
or
SHA384 objSHA
and then CALL The Function (..., objSHA)

看起来很简单,因为它们都是来自同一类型的抽象类。但我缺乏在C#中做到这一点的知识。

感谢的帮助

使您的方法接收基类作为参数:

public String SHA384CheckSum(String pstrFilePath, HashAlgorithm objSHA)

现在,您的调用代码可以这样调用它:

bool useSha256 = false; // Initialize this any way you want
using (HashAlgorithm algorithm = useSha256 ? (HashAlgorithm)SHA256.Create() : SHA384.Create())
{
string checksum = SHA384CheckSum(pstrFilePath, algorithm);
}

显然,SHA384CheckSum不再是这个函数的好名字,所以下一步是重命名它

最新更新