github.com/searKing/golang/go@v1.2.117/crypto/rand/string_crypto.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rand
     6  
     7  import (
     8  	"crypto/rand"
     9  	"math/big"
    10  )
    11  
    12  // take in a character set and a length and will generate a random string using that character set.
    13  func StringCryptoWithCharset(length int64, charset string) (string, error) {
    14  
    15  	maxBigInt := big.NewInt(int64(len(charset)))
    16  
    17  	b := make([]byte, length)
    18  	for i := range b {
    19  		r, err := rand.Int(rand.Reader, maxBigInt)
    20  		if err != nil {
    21  			return "", err
    22  		}
    23  		b[i] = charset[r.Int64()]
    24  	}
    25  	return string(b), nil
    26  }
    27  
    28  // only take in a length, and will use a default characters set to generate a random string
    29  func StringCrypto(length int64) (string, error) {
    30  	return StringCryptoWithCharset(length, CharsetAlphaNum)
    31  }