c# - sha256 : 如何使用算法作为输入
问题描述
好的,这是我的问题。我知道如何使用 C# 进行 HASH,我将此函数用于 Hash Files 并提供进度条:
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
这个函数已经不再是个好名字了,所以下一步就是重命名它。
推荐阅读
- dart - 如何在flutter中读取txt文件?
- list - 将邻接表转为元组数组 Haskell
- javascript - Wordpress 媒体上传错误:“上传时出错。请稍后再试”
- python - 如何使用字典作为量规来使用 pd.apply() 为数据框分配值
- rust - 有没有办法在使用 Serde 反序列化对象时省略包装器/根对象?
- eclipse - CVS 忽略 .git 文件夹
- python - 将代码转换为 python 3,其中 str 和 bytes 不能再连接
- amazon-ec2 - 在 Jupyter 笔记本中禁用“上传”
- json - 编码适用于 1 而不是 Twitter 中使用 python 的其他列表
- reactjs - How to pass extra params to frameworkComponents