Go sha256 salt 如何封装? 代码示范和使用案例

49 min read

使用 Go 语言可以很方便地实现使用 salt 加密 password 的功能,下面是一段示例代码:

package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"math/rand"
	"time"
)

// 生成随机 salt 盐值
func generateSalt() string {
	rand.Seed(time.Now().UnixNano())
	b := make([]byte, 16)
	rand.Read(b)
	return hex.EncodeToString(b)
}

// 加盐哈希处理
func hashedPassword(password string) string {
	salt := generateSalt()
	b := []byte(password + salt)
	hash := sha256.Sum256(b)
	return hex.EncodeToString(hash[:]) + "|" + salt
}

// 验证密码是否正确
func checkPassword(password, hashedPassword string) bool {
	pair := strings.Split(hashedPassword, "|")
	if len(pair) != 2 {
		return false
	}
	hashed, salt := pair[0], pair[1]
	b := []byte(password + salt)
	hash := sha256.Sum256(b)
	return hex.EncodeToString(hash[:]) == hashed
}

func main() {
	password := "password123" // 密码明文
	hashed := hashedPassword(password) // 加密+加盐

	fmt.Println("Original Password: ", password)
	fmt.Println("Hashed Password:   ", hashed)

	// 验证
	result := checkPassword(password, hashed)
	fmt.Println("Password Matched:  ", result)
}

生成的加盐哈希处理结果格式为:hashed password|salt

例如,执行 fmt.Println(hashedPassword("password123")) 可以得到类似于 ee029e09a08bcf217cc3a3f0dccb63cdc7de1341a162d1dd2a243a2586130ca7|fa479923c0f5eda9eee9c1a2e4235230 的结果。

通过 checkPassword 函数可以验证密码是否正确。

password := "password123"
hashed := "ee029e09a08bcf217cc3a3f0dccb63cdc7de1341a162d1dd2a243a2586130ca7|fa479923c0f5eda9eee9c1a2e4235230"

result := checkPassword(password, hashed)
fmt.Println("Password Matched: ", result) // true

这些代码展示了使用 Go 语言实现基于 sha256 和 salt 盐值方式进行密码加密处理和验证的示例。