Go 语言中生成密码

Go 语言中生成特定长度和特定组合的密码

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
29
30
31
32
33
34
35
36
37
38
39
package utils

import (
"fmt"
"math/rand"
"time"
)

const (
NUmStr = "0123456789"
CharStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
SpecStr = "!@#$%&"
)

func GeneratePasswd(length int, charset string) string {
var passwd []byte = make([]byte, length, length)
var sourceStr string

if charset == "num" { // 数字
sourceStr = NUmStr
} else if charset == "char" { // 字母
sourceStr = charset
} else if charset == "mix" { // 数字、字母混合模式
sourceStr = fmt.Sprintf("%s%s", NUmStr, CharStr)
} else if charset == "advance" { // 数字、字母、字符混合模式
sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
} else {
sourceStr = NUmStr
}
// fmt.Println("source:", sourceStr)

// 生成密码
rand.Seed(time.Now().UnixNano())
for i := 0; i < length; i++ {
index := rand.Intn(len(sourceStr))
passwd[i] = sourceStr[index]
}
return string(passwd)
}