59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
|
package random
|
|||
|
|
|||
|
import (
|
|||
|
"math/rand"
|
|||
|
"strings"
|
|||
|
"time"
|
|||
|
)
|
|||
|
|
|||
|
const (
|
|||
|
Digit = "0123456789"
|
|||
|
LowserCase = "abcdefghijklmnopqrstuvwxyz"
|
|||
|
UpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|||
|
Letter = LowserCase + UpperCase
|
|||
|
AlphaNum = Digit + Letter
|
|||
|
Special = " !\"#$%&'()*+’-./:;<=>?@[\\]^_`{|}~"
|
|||
|
All = AlphaNum + Special
|
|||
|
)
|
|||
|
|
|||
|
func choice(charClass []string) string {
|
|||
|
out := strings.Join(charClass, "")
|
|||
|
if len(out) == 0 {
|
|||
|
out = AlphaNum
|
|||
|
}
|
|||
|
|
|||
|
return out
|
|||
|
}
|
|||
|
|
|||
|
func randomer() *rand.Rand {
|
|||
|
return rand.New(rand.NewSource(time.Now().UnixNano()))
|
|||
|
}
|
|||
|
|
|||
|
// Randomize retourne un tableau de taille size
|
|||
|
// et avec des valeurs aléatoires dans available.
|
|||
|
func Randomize[T any](size int, available []T) (out []T) {
|
|||
|
lc, r := len(available), randomer()
|
|||
|
out = make([]T, size)
|
|||
|
|
|||
|
for i := range out {
|
|||
|
out[i] = available[r.Intn(lc)]
|
|||
|
}
|
|||
|
|
|||
|
return
|
|||
|
}
|
|||
|
|
|||
|
// BytesKey génère une clé de bytes.
|
|||
|
func BytesKey(size int, charClass ...string) []byte {
|
|||
|
return Randomize(size, []byte(choice(charClass)))
|
|||
|
}
|
|||
|
|
|||
|
// RunesKey génère une clé de runes.
|
|||
|
func RunesKey(size int, charClass ...string) []rune {
|
|||
|
return Randomize(size, []rune(choice(charClass)))
|
|||
|
}
|
|||
|
|
|||
|
// Key génère une clé sous forme de string.
|
|||
|
func Key(size int, charClass ...string) string {
|
|||
|
return string(RunesKey(size, charClass...))
|
|||
|
}
|