github.com/argoproj/argo-cd@v1.8.7/util/rand/rand.go (about) 1 package rand 2 3 import ( 4 "math/rand" 5 "time" 6 ) 7 8 const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 9 const ( 10 letterIdxBits = 6 // 6 bits to represent a letter index 11 letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits 12 letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits 13 ) 14 15 var src = rand.NewSource(time.Now().UnixNano()) 16 17 // RandString generates, from a given charset, a cryptographically-secure pseudo-random string of a given length. 18 func RandString(n int) string { 19 return RandStringCharset(n, letterBytes) 20 } 21 22 func RandStringCharset(n int, charset string) string { 23 b := make([]byte, n) 24 // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! 25 for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { 26 if remain == 0 { 27 cache, remain = src.Int63(), letterIdxMax 28 } 29 if idx := int(cache & letterIdxMask); idx < len(charset) { 30 b[i] = charset[idx] 31 i-- 32 } 33 cache >>= letterIdxBits 34 remain-- 35 } 36 return string(b) 37 }