You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/generate/generate.go

54 lines
1.0 KiB
Go

4 years ago
package generate
import (
"crypto/rand"
"math/big"
)
// GetRandomString 取得隨機字串
func GetRandomString(n int) (string, error) {
const alphaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
buffer := make([]byte, n)
max := big.NewInt(int64(len(alphaNum)))
for i := 0; i < n; i++ {
index, err := randomInt(max)
if err != nil {
return "", err
}
buffer[i] = alphaNum[index]
}
return string(buffer), nil
}
// GetRandomKey 取得隨機金鑰
func GetRandomKey(n int) (string, error) {
const alphaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()-_=+"
buffer := make([]byte, n)
max := big.NewInt(int64(len(alphaNum)))
for i := 0; i < n; i++ {
index, err := randomInt(max)
if err != nil {
return "", err
}
buffer[i] = alphaNum[index]
}
return string(buffer), nil
}
4 years ago
func randomInt(max *big.Int) (int, error) {
random, err := rand.Int(rand.Reader, max)
if err != nil {
return 0, err
}
return int(random.Int64()), nil
}