使用 7zip sdk 散列解压缩和压缩文件 - c#
Hashing decompressed and compressed files with 7zip sdk - c#
我正在使用7z SDK 来压缩和解压缩文件。
我想在压缩之前读取文件,生成一个sha256哈希,写入文件并压缩它。
解压时,我会读取hash值,存入一个变量,解压文件得到一个新的hash值,与变量中存入的hash值进行比较,检查文件的完整性。
压缩文件时我包含了这个块:
//Write the hash size from the original file
int HashCodeSize = Hash.generateSHA256Hash(input).Length;
byte[] hashSize = BitConverter.GetBytes(HashCodeSize);
output.Write(hashSize, 0, hashSize.Length);
//Write the hash from the original file
byte[] fileHashCode = new byte[8];
fileHashCode = Hash.generateSHA256Hash(input);
output.Write(fileHashCode, 0, fileHashCode.Length);
解压缩文件时我这样做:
//read the hash size from the original file
byte[] hashSize = new byte[4];
input.Read(hashSize, 0, 4);
int sizeOfHash = BitConverter.ToInt16(hashSize, 0);
//Read Hash
byte[] fileHash = new byte[sizeOfHash];
input.Read(fileHash, 0, 8);
当我包含这两个块时,我从 SDK 收到一个 *未处理的异常,
没有它们,程序将完美运行。
这就是我生成哈希的方式:
public static byte[] generateSHA256Hash(Stream fileSource)
{
SHA256 fileHashed = SHA256Managed.Create();
return fileHashed.ComputeHash(fileSource);
}
有谁知道我做错了什么吗?
在写入文件之前将指针移动到文件开头解决了我的问题:
input.Seek(0, SeekOrigin.Begin);
我正在使用7z SDK 来压缩和解压缩文件。 我想在压缩之前读取文件,生成一个sha256哈希,写入文件并压缩它。
解压时,我会读取hash值,存入一个变量,解压文件得到一个新的hash值,与变量中存入的hash值进行比较,检查文件的完整性。
压缩文件时我包含了这个块:
//Write the hash size from the original file
int HashCodeSize = Hash.generateSHA256Hash(input).Length;
byte[] hashSize = BitConverter.GetBytes(HashCodeSize);
output.Write(hashSize, 0, hashSize.Length);
//Write the hash from the original file
byte[] fileHashCode = new byte[8];
fileHashCode = Hash.generateSHA256Hash(input);
output.Write(fileHashCode, 0, fileHashCode.Length);
解压缩文件时我这样做:
//read the hash size from the original file
byte[] hashSize = new byte[4];
input.Read(hashSize, 0, 4);
int sizeOfHash = BitConverter.ToInt16(hashSize, 0);
//Read Hash
byte[] fileHash = new byte[sizeOfHash];
input.Read(fileHash, 0, 8);
当我包含这两个块时,我从 SDK 收到一个 *未处理的异常, 没有它们,程序将完美运行。
这就是我生成哈希的方式:
public static byte[] generateSHA256Hash(Stream fileSource)
{
SHA256 fileHashed = SHA256Managed.Create();
return fileHashed.ComputeHash(fileSource);
}
有谁知道我做错了什么吗?
在写入文件之前将指针移动到文件开头解决了我的问题:
input.Seek(0, SeekOrigin.Begin);