Adler32Helper
Adler32Helper 帮助类
Section titled “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);}Compute(byte[] data)
Section titled “Compute(byte[] data)”计算给定字节数组的 Adler-32 校验和,返回 32 位无符号整数。
public static uint Compute(byte[] data);| 参数名 | 类型 | 描述 |
|---|---|---|
| data | byte[] | 输入字节数组 |
返回值: Adler-32 校验和(32 位无符号整数)。
异常: data 为 null 时抛出 ArgumentNullException。
示例:
using Chet.Security;
byte[] data = "hello"u8.ToArray();uint checksum = Adler32Helper.Compute(data);// checksum: 0x062C0215十六进制校验和
Section titled “十六进制校验和”ComputeHex(byte[] data)
Section titled “ComputeHex(byte[] data)”计算给定字节数组的 Adler-32 校验和,并以 8 字符小写十六进制返回。
public static string ComputeHex(byte[] data);| 参数名 | 类型 | 描述 |
|---|---|---|
| data | byte[] | 输入字节数组 |
返回值: 8 字符长度的小写十六进制校验和。
示例:
using Chet.Security;
byte[] data = "hello"u8.ToArray();string hex = Adler32Helper.ComputeHex(data);// hex: "062c0215"ComputeHex(string text)
Section titled “ComputeHex(string text)”将字符串按 UTF-8 编码后计算 Adler-32 校验和,并以 8 字符小写十六进制返回。
public static string ComputeHex(string text);| 参数名 | 类型 | 描述 |
|---|---|---|
| text | string | 待计算的字符串 |
返回值: 8 字符长度的小写十六进制校验和。
异常: text 为 null 或空字符串时抛出 ArgumentException。
示例:
using Chet.Security;
string hex = Adler32Helper.ComputeHex("hello");// hex: "062c0215"字节数组校验和
Section titled “字节数组校验和”ComputeBytes(byte[] data)
Section titled “ComputeBytes(byte[] data)”计算 Adler-32 校验和,并以 4 字节小端序返回。
public static byte[] ComputeBytes(byte[] data);| 参数名 | 类型 | 描述 |
|---|---|---|
| data | byte[] | 输入字节数组 |
返回值: 4 字节长度的小端序校验和字节数组。
示例:
using Chet.Security;
byte[] bytes = Adler32Helper.ComputeBytes("hello"u8.ToArray());// bytes: [0x15, 0x02, 0x2C, 0x06]ComputeFileHex(string filePath)
Section titled “ComputeFileHex(string filePath)”分块读取文件并计算 Adler-32 校验和,返回 8 字符小写十六进制。
public static string ComputeFileHex(string filePath);| 参数名 | 类型 | 描述 |
|---|---|---|
| filePath | string | 文件绝对或相对路径 |
返回值: 8 字符长度的小写十六进制校验和。
异常: filePath 为 null 或空字符串时抛出 ArgumentException;文件不存在时抛出 FileNotFoundException。
示例:
using Chet.Security;
string hex = Adler32Helper.ComputeFileHex(@"C:\Files\archive.zip");// hex: "00000001"(空文件示例值,依文件内容而定)