写在前面

昨晚上睡觉前我就在想能不能把多个加密算法集成到一个库中,方便开发者调用,说干就干,今天肝了一天,中午直接吃的外卖哈哈哈哈,终于把仓库开源了,欢迎各位Go开发者StarFork!

仓库地址

go-crypto-guard https://github.com/palp1tate/go-crypto-guard

介绍

该存储库包含一个用 Go 编写的综合密码哈希库。该库支持多种哈希算法,包括 PBKDF2(使用 SHA1、SHA256、SHA384、SHA512 和 MD5)、Bcrypt、Scrypt、Argon2、HMAC、Blake2b 和 Blake2s。它允许自定义盐长度、迭代、密钥长度和算法选择。该开源项目旨在为开发人员提供用于安全密码存储和验证的多功能工具。尤其是后端开发人员,在实现登录注册业务中通常会遇到密码加密和验证的问题,该库可以很好的解决这个问题,功能强大。为了更方便的想使用什么算法就使用什么算法(含加盐),于是这个仓库就横空出世了。

支持的算法:

password的格式与Django内置的加密算法格式相同:

1
<algorithm>$<iterations>$<salt>$<hash>

安装

1
go get github.com/palp1tate/go-crypto-guard 

用法

下面提供了一些用法示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
"fmt"
"github.com/palp1tate/go-crypto-guard"
)

func main() {
originPwd := "123456"
options := pwd.Options{
SaltLen: 16,
KeyLen: 32,
Iterations: 100,
Algorithm: pwd.SHA512,
}
encodedPwd, err := pwd.Generate(originPwd, &options)
if err != nil {
fmt.Println(err)
}

fmt.Println("Encoded password:", encodedPwd)

if ok, err := pwd.Verify(originPwd, encodedPwd); err != nil {
fmt.Println(err)
} else {
fmt.Println("Verify result:", ok)
}
}

对于SHA512、SHA256、SHA1、SHA384、Md5、Argon2,可以填写全部参数,也可以不完全填写。但对于其他算法,它们不需要那么多参数,你甚至可以只用指定具体的算法:

1
2
3
4
5
6
7
8
9
10
11
//Bcrypt
options := pwd.Options{
Algorithm: pwd.Bcrypt,
}

//HMAC
options := pwd.Options{
Algorithm: pwd.HMAC,
}

//...

Options定义用于自定义密码散列过程的参数。每个字段都有一个默认值,即使您不传递参数也是如此。

1
2
3
4
5
6
7
8
9
10
11
// Fields:
// - SaltLen: Length of the salt to be generated for password hashing.
// - Iterations: Number of iterations to apply during the hashing process.
// - KeyLen: Length of the derived key produced by the hashing algorithm.
// - Algorithm: The specific hashing algorithm to be used for password hashing.
type Options struct {
SaltLen int // Defaults to 16.
Iterations int // Defaults to 50.
KeyLen int // Defaults to 32.
Algorithm Algorithm // Defaults to "SHA512".
}

未来的计划

计划在未来的版本中加入更多的哈希算法,以满足不同的场景和需求。以下是可能考虑的一些算法:

也有考虑出一个Python版本。

请注意,这只是一个计划,可能会根据项目需求和社区反馈进行更改。将通过 GitHub 存储库向用户通报任何更改或添加的最新情况。