Remove error returns from crypto random helpers and callers (#37240)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: wxiaoguang <2114189+wxiaoguang@users.noreply.github.com> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: silverwind <115237+silverwind@users.noreply.github.com>
This commit is contained in:
+11
-17
@@ -61,48 +61,42 @@ func NormalizeEOL(input []byte) []byte {
|
||||
}
|
||||
|
||||
// CryptoRandomInt returns a crypto random integer between 0 and limit, inclusive
|
||||
func CryptoRandomInt(limit int64) (int64, error) {
|
||||
func CryptoRandomInt(limit int64) int64 {
|
||||
rInt, err := rand.Int(rand.Reader, big.NewInt(limit))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
panic(err) // this should never happen
|
||||
}
|
||||
return rInt.Int64(), nil
|
||||
return rInt.Int64()
|
||||
}
|
||||
|
||||
const alphanumericalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
|
||||
// CryptoRandomString generates a crypto random alphanumerical string, each byte is generated by [0,61] range
|
||||
func CryptoRandomString(length int64) (string, error) {
|
||||
func CryptoRandomString(length int64) string {
|
||||
const alphanumericalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
buf := make([]byte, length)
|
||||
limit := int64(len(alphanumericalChars))
|
||||
for i := range buf {
|
||||
num, err := CryptoRandomInt(limit)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
num := CryptoRandomInt(limit)
|
||||
buf[i] = alphanumericalChars[num]
|
||||
}
|
||||
return string(buf), nil
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
// CryptoRandomBytes generates `length` crypto bytes
|
||||
// This differs from CryptoRandomString, as each byte in CryptoRandomString is generated by [0,61] range
|
||||
// This function generates totally random bytes, each byte is generated by [0,255] range
|
||||
// TODO: it never fails, remove the "error" in the future
|
||||
func CryptoRandomBytes(length int64) ([]byte, error) {
|
||||
func CryptoRandomBytes(length int64) []byte {
|
||||
buf := make([]byte, length)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
panic(err) // this should never happen, "rand.Read" never fails
|
||||
}
|
||||
return buf, nil
|
||||
return buf
|
||||
}
|
||||
|
||||
var chaCha8RandPool = sync.OnceValue(func() *sync.Pool {
|
||||
return &sync.Pool{
|
||||
New: func() any {
|
||||
var buf [32]byte
|
||||
_, _ = rand.Read(buf[:])
|
||||
return rand2.NewChaCha8(buf)
|
||||
seed := CryptoRandomBytes(32)
|
||||
return rand2.NewChaCha8([32]byte(seed))
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user