hash

package
v0.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 26, 2026 License: BSD-2-Clause Imports: 9 Imported by: 0

README

Hash 哈希工具包

提供多种哈希算法(MD5、SHA1、SHA256、SHA512)、HMAC 签名计算和 Bcrypt 密码哈希功能的 Go 语言工具包。

特性

  • 多种哈希算法 - 支持 MD5、SHA1、SHA256、SHA512 四种常用哈希算法
  • HMAC 签名计算 - 支持基于各种哈希算法的 HMAC 签名计算
  • Bcrypt 密码哈希 - 提供安全的密码哈希和验证功能,适用于密码存储场景
  • 泛型编程支持 - 使用 Go 泛型特性,提供类型安全且灵活的 API
  • 多种输出格式 - 支持原始字节数组、十六进制字符串等多种输出格式
  • 流式处理 - 支持从 io.Reader 直接计算哈希值,适合处理大文件
  • 便捷方法 - 提供默认实例 hash.Hash,开箱即用

快速开始

基本哈希计算
import "github.com/lite-lake/litecore-go/util/hash"

// 计算字符串哈希值
md5Hash := hash.Hash.MD5String("hello world")
sha256Hash := hash.Hash.SHA256String("hello world")

// 返回原始字节数组
hashBytes := hash.Hash.SHA256("hello world")
HMAC 签名
// HMAC-SHA256 签名
signature := hash.Hash.HMACSHA256String("data", "secret-key")

// 验证签名
expectedSignature := hash.Hash.HMACSHA256String("data", "secret-key")
isValid := signature == expectedSignature
密码哈希(Bcrypt)
// 生成密码哈希值
hashedPassword, err := hash.Hash.BcryptHash("mypassword")
if err != nil {
    log.Fatal(err)
}

// 验证密码
isValid := hash.Hash.BcryptVerify("mypassword", hashedPassword)
大文件处理
file, err := os.Open("large-file.dat")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

// 计算文件哈希值
hashString, err := hash.HashReaderStringGeneric(file, hash.SHA256Algorithm{})
if err != nil {
    log.Fatal(err)
}

支持的哈希算法

MD5

输出长度:32 字符(十六进制)

使用场景

  • 非安全场景的校验和(如文件完整性校验、缓存键生成)
  • 已不适用于安全相关场景(已被证明存在安全漏洞)
// 完整长度(32字符)
hash.Hash.MD5String("data")

// 16位短格式
hash.Hash.MD5String16("data")

// 32位格式
hash.Hash.MD5String32("data")

// 返回字节数组
hash.Hash.MD5("data")
SHA1

输出长度:40 字符(十六进制)

使用场景

  • 遗留系统兼容
  • 不推荐在新项目中使用(存在安全漏洞)
// 完整长度(40字符)
hash.Hash.SHA1String("data")

// 返回字节数组
hash.Hash.SHA1("data")
SHA256

输出长度:64 字符(十六进制)

使用场景

  • 推荐用于大多数安全场景
  • 数字签名、API 签名验证
  • 数据完整性校验
  • 密码派生(需配合盐值)
// 完整长度(64字符)
hash.Hash.SHA256String("data")

// 返回字节数组
hash.Hash.SHA256("data")
SHA512

输出长度:128 字符(十六进制)

使用场景

  • 高安全要求场景
  • 需要更长哈希值的应用
  • 大数据量处理
// 完整长度(128字符)
hash.Hash.SHA512String("data")

// 返回字节数组
hash.Hash.SHA512("data")
Bcrypt

输出长度:60 字符(包含算法版本、成本因子、盐值和哈希值)

使用场景

  • 密码存储(专为密码设计)
  • 每次生成不同的哈希值(包含随机盐值)
  • 支持可调节的计算成本因子
// 使用默认成本因子生成密码哈希
hashedPassword, err := hash.Hash.BcryptHash("mypassword")

// 指定成本因子(4-31,默认为 10)
hashedPassword, err := hash.Hash.BcryptHashWithCost("mypassword", 12)

// 验证密码
isValid := hash.Hash.BcryptVerify("mypassword", hashedPassword)

注意事项

  • Bcrypt 是专门为密码哈希设计的算法,每次生成的哈希值不同(包含随机盐值)
  • 成本因子越高,计算时间越长,安全性越高
  • 默认成本因子为 hash.BcryptDefaultCost(值为 10)

HMAC 签名

HMAC(基于哈希的消息认证码)用于验证数据完整性和真实性。

// HMAC-MD5
hash.Hash.HMACMD5String("data", "key")

// HMAC-SHA1
hash.Hash.HMACSHA1String("data", "key")

// HMAC-SHA256(推荐用于 API 签名)
hash.Hash.HMACSHA256String("data", "key")

// HMAC-SHA512
hash.Hash.HMACSHA512String("data", "key")

// 返回字节数组
hash.Hash.HMACSHA256("data", "key")

使用场景

  • API 签名验证
  • 消息认证
  • 令牌验证
  • 防篡改校验

输出格式

// FormatBytes: 原始字节数组
bytesHash := hash.HashHexGeneric("data", hash.MD5Algorithm{}, hash.FormatBytes)

// FormatHexShort: 16位十六进制字符串
shortHash := hash.HashHexGeneric("data", hash.MD5Algorithm{}, hash.FormatHexShort)

// FormatHexMedium: 32位十六进制字符串
mediumHash := hash.HashHexGeneric("data", hash.MD5Algorithm{}, hash.FormatHexMedium)

// FormatHexFull: 完整长度十六进制字符串(默认)
fullHash := hash.HashHexGeneric("data", hash.MD5Algorithm{}, hash.FormatHexFull)

泛型函数

哈希计算
// 计算任意哈希算法的值
hashBytes := hash.HashGeneric("data", hash.SHA256Algorithm{})

// 指定输出格式
hashString := hash.HashHexGeneric("data", hash.SHA256Algorithm{}, hash.FormatHexFull)

// 处理字节数组
hashBytes = hash.HashBytesGeneric([]byte("data"), hash.SHA256Algorithm{})

// 处理 io.Reader(大文件)
file, _ := os.Open("file.txt")
hashBytes, err := hash.HashReaderGeneric(file, hash.SHA256Algorithm{})
HMAC 计算
// HMAC 泛型函数
hmacBytes := hash.HMACGeneric("data", "key", hash.SHA256Algorithm{})
hmacString := hash.HMACStringGeneric("data", "key", hash.SHA256Algorithm{})

// 处理字节数组
hmacBytes = hash.HMACBytesGeneric([]byte("data"), []byte("key"), hash.SHA256Algorithm{})

// 处理 io.Reader
file, _ := os.Open("file.txt")
hmacBytes, err := hash.HMACReaderGeneric(file, []byte("key"), hash.SHA256Algorithm{})
自定义算法
// 实现自定义哈希算法
type CustomAlgorithm struct{}

func (CustomAlgorithm) Hash() hash.Hash {
    return sha3.New256()
}

// 使用自定义算法
result := hash.HashGeneric("data", CustomAlgorithm{})

使用场景

密码存储和验证
// 用户注册时生成密码哈希
hashedPassword, err := hash.Hash.BcryptHash("user-password")
if err != nil {
    log.Fatal(err)
}

// 存储到数据库
db.SaveUser(username, hashedPassword)

// 用户登录时验证密码
storedHash := db.GetUserPassword(username)
isValid := hash.Hash.BcryptVerify("user-input-password", storedHash)
if isValid {
    // 登录成功
}
API 签名验证
// 生成 API 签名
func GenerateAPISignature(data string, secretKey string) string {
    return hash.Hash.HMACSHA256String(data, secretKey)
}

// 验证 API 签名
func VerifyAPISignature(data string, signature string, secretKey string) bool {
    expectedSignature := GenerateAPISignature(data, secretKey)
    return expectedSignature == signature
}
文件完整性校验
// 计算文件哈希值
func CalculateFileHash(filePath string) (string, error) {
    file, err := os.Open(filePath)
    if err != nil {
        return "", err
    }
    defer file.Close()

    return hash.HashReaderStringGeneric(file, hash.SHA256Algorithm{})
}

// 验证文件完整性
func VerifyFileIntegrity(filePath string, expectedHash string) (bool, error) {
    actualHash, err := CalculateFileHash(filePath)
    if err != nil {
        return false, err
    }
    return actualHash == expectedHash, nil
}
缓存键生成
func GenerateCacheKey(prefix string, params ...string) string {
    key := prefix
    for _, param := range params {
        key += ":" + param
    }
    // 使用 MD5 短格式作为缓存键
    return hash.Hash.MD5String16(key)
}

cacheKey := GenerateCacheKey("user", "123", "profile")
数据去重
func GetDataUniqueID(data string) string {
    return hash.Hash.SHA256String(data)
}

// 使用 map 记录已处理的数据哈希
seenHashes := make(map[string]bool)

func ProcessData(data string) {
    dataHash := GetDataUniqueID(data)
    if seenHashes[dataHash] {
        return // 数据已处理
    }
    // 处理数据
    seenHashes[dataHash] = true
}

性能考虑

算法选择
算法 速度 安全性 推荐场景
MD5 最快 已不安全 仅适用于非安全场景的校验和
SHA1 较快 已不推荐 避免在新项目中使用
SHA256 中等 安全 推荐用于大多数场景
SHA512 较慢 最安全 高安全要求场景
Bcrypt 密码安全 密码存储(专为密码设计)
大文件处理

对于大文件,建议使用 io.Reader 接口的函数,避免将整个文件加载到内存:

file, _ := os.Open("large-file.dat")
defer file.Close()

hashString, err := hash.HashReaderStringGeneric(file, hash.SHA256Algorithm{})
批量计算

如果需要计算多个哈希值,可以考虑并行处理以提高性能。

注意事项

  1. 安全性:MD5 和 SHA1 已被证明存在安全漏洞,不应在安全敏感场景中使用
  2. 密码存储:对于密码存储,必须使用 Bcrypt 等专门的密码哈希算法
  3. 错误处理:使用 io.Reader 相关函数时,务必处理可能的错误
  4. 字符编码:确保输入数据的字符编码一致,避免因编码不同导致哈希结果不同
  5. 密钥管理:使用 HMAC 时,妥善保管密钥,避免硬编码在代码中
  6. Bcrypt 成本因子:根据实际需求选择合适的成本因子,默认为 10

运行测试

# 运行所有测试
go test ./util/hash

# 运行测试并显示覆盖率
go test -cover ./util/hash

# 运行性能基准测试
go test -bench=. ./util/hash

# 查看详细的测试输出
go test -v ./util/hash

# 运行特定测试
go test ./util/hash -run TestBcryptHash

Documentation

Overview

Package hash 提供多种哈希算法和HMAC计算功能,支持泛型编程

核心特性:

  • 支持多种哈希算法:MD5、SHA1、SHA256、SHA512
  • 支持HMAC(基于哈希的消息认证码)计算
  • 支持Bcrypt密码哈希(用于安全的密码存储和验证)
  • 提供泛型函数,可扩展支持自定义哈希算法
  • 支持多种输出格式:原始字节、16位/32位/完整长度十六进制字符串
  • 提供便捷方法,通过 util.Hash 实例快速调用
  • 支持 io.Reader 数据源,可处理流式数据

基本用法:

// 计算SHA256哈希值(返回十六进制字符串)
hashStr := util.Hash.SHA256String("hello world")
fmt.Println(hashStr) // b94d27b9...

// 计算HMAC-SHA256(需要密钥)
hmacStr := util.Hash.HMACSHA256String("data", "secret-key")
fmt.Println(hmacStr)

// 计算MD5并返回16位短格式
md5Short := util.Hash.MD5String16("filename")

// 使用 Bcrypt 哈希密码(安全存储)
hashedPassword, err := util.Hash.BcryptHash("mypassword")
if err != nil {
    logger.Fatal("密码哈希失败", "error", err)
}
// 验证密码
isValid := util.Hash.BcryptVerify("mypassword", hashedPassword)

// 使用泛型函数计算哈希值
hashBytes := hash.HashGeneric("data", hash.SHA256Algorithm{})

// 从文件计算哈希值
file, _ := os.Open("file.txt")
defer file.Close()
fileHash, err := hash.HashReaderStringGeneric(file, hash.SHA256Algorithm{})
if err != nil {
    logger.Fatal("文件哈希计算失败", "error", err)
}

泛型支持:

通过泛型函数 HashGeneric 和 HMACGeneric,可以扩展支持自定义哈希算法。
只需实现 HashAlgorithm 接口即可:

type CustomAlgorithm struct{}
func (CustomAlgorithm) Hash() hash.Hash {
    return sha3.New256() // 或其他哈希算法
}

result := hash.HashGeneric("data", CustomAlgorithm{})

输出格式:

Package hash 支持以下输出格式:
  - FormatBytes: 原始字节数组
  - FormatHexShort: 16位十六进制字符串(常用于MD5短格式)
  - FormatHexMedium: 32位十六进制字符串
  - FormatHexFull: 完整长度十六进制字符串(默认)

Index

Constants

View Source
const BcryptDefaultCost = bcrypt.DefaultCost

BcryptDefaultCost 默认 bcrypt 成本因子

Variables

View Source
var Hash = &hashEngine{}

Hash 默认的哈希操作实例

Functions

func HMACBytesGeneric

func HMACBytesGeneric[T HashAlgorithm](data []byte, key []byte, algorithm T) []byte

HMACBytesGeneric 计算字节数组的HMAC哈希值

func HMACBytesHexGeneric

func HMACBytesHexGeneric[T HashAlgorithm](data []byte, key []byte, algorithm T, format HashOutputFormat) string

HMACBytesHexGeneric 计算字节数组的HMAC哈希值并返回指定格式的十六进制字符串

func HMACGeneric

func HMACGeneric[T HashAlgorithm](data string, key string, algorithm T) []byte

HMACGeneric 计算HMAC哈希值

func HMACHexGeneric

func HMACHexGeneric[T HashAlgorithm](data string, key string, algorithm T, format HashOutputFormat) string

HMACHexGeneric 计算HMAC哈希值并返回指定格式的十六进制字符串

func HMACReaderGeneric

func HMACReaderGeneric[T HashAlgorithm](r io.Reader, key []byte, algorithm T) ([]byte, error)

HMACReaderGeneric 从io.Reader计算HMAC哈希值

func HMACReaderHexGeneric

func HMACReaderHexGeneric[T HashAlgorithm](r io.Reader, key []byte, algorithm T,
	format HashOutputFormat) (string, error)

HMACReaderHexGeneric 从io.Reader计算HMAC哈希值并返回指定格式的十六进制字符串

func HMACReaderStringGeneric

func HMACReaderStringGeneric[T HashAlgorithm](r io.Reader, key []byte, algorithm T) (string, error)

HMACReaderStringGeneric 从io.Reader计算HMAC并返回完整十六进制字符串

func HMACStringGeneric

func HMACStringGeneric[T HashAlgorithm](data string, key string, algorithm T) string

HMACStringGeneric 计算HMAC并返回完整十六进制字符串

func HashBytesGeneric

func HashBytesGeneric[T HashAlgorithm](data []byte, algorithm T) []byte

HashBytesGeneric 计算字节数组的哈希值

func HashBytesHexGeneric

func HashBytesHexGeneric[T HashAlgorithm](data []byte, algorithm T, format HashOutputFormat) string

HashBytesHexGeneric 计算字节数组的哈希值并返回指定格式的十六进制字符串

func HashGeneric

func HashGeneric[T HashAlgorithm](data string, algorithm T) []byte

HashGeneric 计算任意哈希算法的值

func HashHexGeneric

func HashHexGeneric[T HashAlgorithm](data string, algorithm T, format HashOutputFormat) string

HashHexGeneric 计算哈希值并返回指定格式的十六进制字符串

func HashReaderGeneric

func HashReaderGeneric[T HashAlgorithm](r io.Reader, algorithm T) ([]byte, error)

HashReaderGeneric 从io.Reader计算哈希值

func HashReaderHexGeneric

func HashReaderHexGeneric[T HashAlgorithm](r io.Reader, algorithm T, format HashOutputFormat) (string, error)

HashReaderHexGeneric 从io.Reader计算哈希值并返回指定格式的十六进制字符串

func HashReaderStringGeneric

func HashReaderStringGeneric[T HashAlgorithm](r io.Reader, algorithm T) (string, error)

HashReaderStringGeneric 从io.Reader计算哈希并返回完整十六进制字符串

func HashStringGeneric

func HashStringGeneric[T HashAlgorithm](data string, algorithm T) string

HashStringGeneric 计算哈希并返回完整十六进制字符串

Types

type HashAlgorithm

type HashAlgorithm interface {
	Hash() hash.Hash
}

HashAlgorithm 哈希算法接口

type HashOutputFormat

type HashOutputFormat int

HashOutputFormat 哈希输出格式枚举

const (
	// FormatBytes 原始字节数组格式
	FormatBytes HashOutputFormat = iota
	// FormatHexShort 16位十六进制字符串(通常用于MD5短格式)
	FormatHexShort
	// FormatHexMedium 32位十六进制字符串(通常用于MD5、SHA256短格式)
	FormatHexMedium
	// FormatHexFull 完整长度十六进制字符串
	FormatHexFull
)

type MD5Algorithm

type MD5Algorithm struct{}

MD5Algorithm MD5算法实现

func (MD5Algorithm) Hash

func (MD5Algorithm) Hash() hash.Hash

type SHA1Algorithm

type SHA1Algorithm struct{}

SHA1Algorithm SHA1算法实现

func (SHA1Algorithm) Hash

func (SHA1Algorithm) Hash() hash.Hash

type SHA256Algorithm

type SHA256Algorithm struct{}

SHA256Algorithm SHA256算法实现

func (SHA256Algorithm) Hash

func (SHA256Algorithm) Hash() hash.Hash

type SHA512Algorithm

type SHA512Algorithm struct{}

SHA512Algorithm SHA512算法实现

func (SHA512Algorithm) Hash

func (SHA512Algorithm) Hash() hash.Hash

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL