69 lines
2.2 KiB
Go
69 lines
2.2 KiB
Go
package random
|
|
|
|
import (
|
|
"math/rand"
|
|
"strings"
|
|
)
|
|
|
|
// Standard character set.
|
|
const (
|
|
CharsetAlpha string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
CharsetAlphanumeric string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
CharsetAlphaLower string = "abcdefghijklmnopqrstuvwxyz"
|
|
CharsetAlphaUpper string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
CharsetNumeric string = "0123456789"
|
|
CharsetSymbols string = "!@#$%^&*()-=_+[]{};:,.<>/?"
|
|
)
|
|
|
|
// Alpha generates a random string of the specified length using a mixed-case alphabetical character set.
|
|
var Alpha = String([]rune(CharsetAlpha))
|
|
|
|
// Alphanumeric generates a random string of the specified length using an alphanumeric character set.
|
|
var Alphanumeric = String([]rune(CharsetAlphanumeric))
|
|
|
|
// AlphaLower generates a random string of the specified length using a lowercase alphabetical character set.
|
|
var AlphaLower = String([]rune(CharsetAlphaLower))
|
|
|
|
// AlphaUpper generates a random string of the specified length using an uppercase alphabetical character set.
|
|
var AlphaUpper = String([]rune(CharsetAlphaUpper))
|
|
|
|
// Numeric generates a random string of the specified length containing numbers only.
|
|
var Numeric = String([]rune(CharsetNumeric))
|
|
|
|
// Password generates a random string of the specified length, including the specified counts of numbers and symbols.
|
|
func Password(length, numbers, symbols int) string {
|
|
parts := []string{
|
|
Alpha(length - numbers - symbols),
|
|
Numeric(numbers),
|
|
Symbols(symbols),
|
|
}
|
|
|
|
str := strings.Join(parts, "")
|
|
m := map[int]rune{}
|
|
for i, c := range str {
|
|
m[i] = c
|
|
}
|
|
|
|
jumbled := []rune{}
|
|
for _, c := range m {
|
|
jumbled = append(jumbled, c)
|
|
}
|
|
|
|
return string(jumbled)
|
|
}
|
|
|
|
// String returns a function that can be used to generate a random string of the specified length using the given character set.
|
|
func String(chars []rune) func(length int) string {
|
|
max := len(chars)
|
|
return func(length int) string {
|
|
s := make([]rune, length)
|
|
for i := range s {
|
|
s[i] = chars[rand.Intn(max)]
|
|
}
|
|
return string(s)
|
|
}
|
|
}
|
|
|
|
// Symbols generates a random string of the specified length using a limited selection of symbols.
|
|
var Symbols = String([]rune(CharsetSymbols))
|