爲了避免把所有的文件到像Dabblernl的解決方案的內存,你需要使用一個FileStream在這討論過質疑Computing MD5SUM of large files in C#,但MD5CryptoServiceProvider不允許你額外的數據添加到末尾。
因此,你需要一個合併的流這樣的:
public class MergedStream : Stream, IDisposable
{
Stream s1;
Stream s2;
public MergedStream(Stream first, Stream second)
{
s1 = first;
s2 = second;
}
public override int Read(byte[] buffer, int offset, int count)
{
int s1count = (int)Math.Min((long)count, s1.Length - s1.Position);
int bytesRead = 0;
if (s1count > 0)
{
bytesRead += s1.Read(buffer, offset, s1count);
}
if (s1count < count)
{
bytesRead += s2.Read(buffer, offset + s1count, count - s1count);
}
return bytesRead;
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get { return s1.CanRead && s2.CanRead; }
}
public override bool CanSeek
{
get { return s1.CanSeek && s2.CanSeek; }
}
public override bool CanWrite
{
get { return s1.CanWrite && s2.CanWrite; }
}
public override void Flush()
{
s1.Flush();
s2.Flush();
}
public override long Length
{
get { return s1.Length + s2.Length; }
}
public override long Position
{
get
{
return s1.Position + s2.Position;
}
set
{
throw new NotImplementedException();
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
void IDisposable.Dispose()
{
s1.Dispose();
s2.Dispose();
}
}
然後您可以使用像這樣的食鹽,文件哈希
FileStream fs = new FileStream(@"c:\text.txt", FileMode.Open);
var m = new MemoryStream(ToAnsiiBytes("SALT"), false);
var ms = new MergedStream(fs, m);
var C = hasher.ComputeHash(ms);
PrintHash(Console.Out, C);
與ToAnsiiBytes和PrintHash擺明實用的功能,例如:
和
public static void PrintHash(TextWriter op, byte[] hash)
{
foreach (byte b in hash)
{
op.Write("{0:X2}", b);
}
}
當文件c:\的text.txt包含文本TOTO可以運行這個程序,看看文件+鹽等於相同的文字「totoSALT」
FileStream fs = new FileStream(@"c:\text.txt", FileMode.Open);
var hasher = new MD5CryptoServiceProvider();
var A = hasher.ComputeHash(fs);
PrintHash(Console.Out, A);
Console.Out.WriteLine();
var salt = new byte[] { 0x53, 0x41, 0x4C, 0x54 };
var B = hasher.ComputeHash(ToAnsiiBytes("SALT"));
PrintHash(Console.Out, B);
Console.Out.WriteLine();
var m = new MemoryStream(ToAnsiiBytes("SALT"), false);
fs.Seek(0, SeekOrigin.Begin);
var ms = new MergedStream(fs, m);
var C = hasher.ComputeHash(ms);
PrintHash(Console.Out, C);
Console.Out.WriteLine();
HashAndPrint(Console.Out, "toto");
HashAndPrint(Console.Out, "totoSALT");
HashAndPrint(Console.Out, "SALT");
與此輸出
F71DBE52628A3F83A77AB494817525C6
8C4F4370C53E0C1E1AE9ACD577DDDBED
308DB2451D6580FEEB09FCF2DC1CEE19
F71DBE52628A3F83A77AB494817525C6 = toto
308DB2451D6580FEEB09FCF2DC1CEE19 = totoSALT
8C4F4370C53E0C1E1AE9ACD577DDDBED = SALT
我不知道是否有鹽特定方式的算法。但是你可以很容易地創建自己的Stream類來包裝給定的Stream對象。當詢問最初的幾個字節時,包裝器對象可以提供salt字節,然後開始提取底層流字節。 – 2009-05-18 18:48:59
在這種情況下,根據給出的信息,鹽是不必要的,並且可能無法實現(回想一下鹽需要與* salthashed數據一起存儲)。 – yfeldblum 2009-11-14 17:51:15