Skip to content

Instantly share code, notes, and snippets.

@yougg
Created July 30, 2018 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yougg/c15c7ed3cfeb454bf3d738362a8aed36 to your computer and use it in GitHub Desktop.
Save yougg/c15c7ed3cfeb454bf3d738362a8aed36 to your computer and use it in GitHub Desktop.
generate random string in go
package main
import (
"math/rand"
"time"
"fmt"
)
const (
lowercaseLetter = `abcdefghijklmnopqrstuvwxyz`
uppercaseLetter = `ABCDEFGHIJKLMNOPQRSTUVWXYZ`
digital = `0123456789`
specialSymbols = `@-_`
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
fmt.Println(RandString(4))
fmt.Println(RandString(8))
fmt.Println(RandString(16))
fmt.Println(RandString(32))
}
// RandString 生成指定长度(length)的随机密码pwd
// 密码长度为 4~64位, 超范围返回空密码
// 密码包含以下必选项:
// 小写字母: a-z
// 大写字母: A-Z
// 印度数字: 0-9
// 特殊符号: @-_
func RandString(length int) (pwd string) {
if length < 4 || length > 64 {
return
}
// 1. 随机分配4种类型字符的数量
assign := [...]int{1, 1, 1, 1}
types := len(assign)
for i := 0; i < (length - 4); i++ {
assign[rand.Intn(types)]++
}
sum := 0
for _, v := range assign {
sum += v
}
if length != sum {
return
}
// 2. 根据各类型字符的数量,随机填充密码
chars := [][]byte{
[]byte(lowercaseLetter),
[]byte(specialSymbols),
[]byte(uppercaseLetter),
[]byte(digital),
}
pwds := make([]byte, length)
index := 0
for i := range pwds {
if types > 1 {
index = rand.Intn(types)
} else {
index = 0
}
pwds[i] = chars[index][rand.Intn(len(chars[index]))]
if assign[index]--; assign[index] <= 0 {
types--
assign[index], assign[types] = assign[types], assign[index]
chars[index], chars[types] = chars[types], chars[index]
}
}
// 3. 随机打乱生成的密码序
for i := range pwds {
n := rand.Intn(length)
pwds[i], pwds[n] = pwds[n], pwds[i]
}
pwd = string(pwds)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment