Add generate random key

tags/v1.4.0 v1.4.0
Stanly 3 years ago
parent 2edb855dd1
commit e832a78b72

@ -24,6 +24,25 @@ func GetRandomString(n int) (string, error) {
return string(buffer), nil 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
}
func randomInt(max *big.Int) (int, error) { func randomInt(max *big.Int) (int, error) {
random, err := rand.Int(rand.Reader, max) random, err := rand.Int(rand.Reader, max)
if err != nil { if err != nil {

Loading…
Cancel
Save