跳转到内容

Adler32Helper

Adler32Helper 是一个静态帮助类,提供 Adler-32 校验和算法(zlib 算法)的计算能力,采用模数 65521,适用于数据完整性校验、文件指纹等非安全用途。

  • 🔢 标准算法 — zlib 算法,模数 65521,初始 a=1、b=0
  • 📝 多输入支持 — 接受字节数组、字符串(UTF-8 编码)输入
  • 🎨 多输出格式 — 支持无符号整数、8 字符小写十六进制、4 字节小端序字节数组
  • 📁 文件校验 — 分块读取文件流计算校验和(8KB 缓冲),适合大文件
  • ⚡ 轻量实现 — 简洁的累加 + 取模运算,无需预计算查找表
  • 🌐 多目标框架 — 同时支持 netstandard2.1 与 net8.0
namespace Chet.Security;
public static class Adler32Helper
{
public static uint Compute(byte[] data);
public static string ComputeHex(byte[] data);
public static string ComputeHex(string text);
public static string ComputeFileHex(string filePath);
public static byte[] ComputeBytes(byte[] data);
}

计算给定字节数组的 Adler-32 校验和,返回 32 位无符号整数。

public static uint Compute(byte[] data);
参数名类型描述
databyte[]输入字节数组

返回值: Adler-32 校验和(32 位无符号整数)。

异常: data 为 null 时抛出 ArgumentNullException。

示例:

using Chet.Security;
byte[] data = "hello"u8.ToArray();
uint checksum = Adler32Helper.Compute(data);
// checksum: 0x062C0215

计算给定字节数组的 Adler-32 校验和,并以 8 字符小写十六进制返回。

public static string ComputeHex(byte[] data);
参数名类型描述
databyte[]输入字节数组

返回值: 8 字符长度的小写十六进制校验和。

示例:

using Chet.Security;
byte[] data = "hello"u8.ToArray();
string hex = Adler32Helper.ComputeHex(data);
// hex: "062c0215"

将字符串按 UTF-8 编码后计算 Adler-32 校验和,并以 8 字符小写十六进制返回。

public static string ComputeHex(string text);
参数名类型描述
textstring待计算的字符串

返回值: 8 字符长度的小写十六进制校验和。

异常: text 为 null 或空字符串时抛出 ArgumentException。

示例:

using Chet.Security;
string hex = Adler32Helper.ComputeHex("hello");
// hex: "062c0215"

计算 Adler-32 校验和,并以 4 字节小端序返回。

public static byte[] ComputeBytes(byte[] data);
参数名类型描述
databyte[]输入字节数组

返回值: 4 字节长度的小端序校验和字节数组。

示例:

using Chet.Security;
byte[] bytes = Adler32Helper.ComputeBytes("hello"u8.ToArray());
// bytes: [0x15, 0x02, 0x2C, 0x06]

分块读取文件并计算 Adler-32 校验和,返回 8 字符小写十六进制。

public static string ComputeFileHex(string filePath);
参数名类型描述
filePathstring文件绝对或相对路径

返回值: 8 字符长度的小写十六进制校验和。

异常: filePath 为 null 或空字符串时抛出 ArgumentException;文件不存在时抛出 FileNotFoundException。

示例:

using Chet.Security;
string hex = Adler32Helper.ComputeFileHex(@"C:\Files\archive.zip");
// hex: "00000001"(空文件示例值,依文件内容而定)