github.com/searKing/golang/go@v1.2.117/crypto/rand/string.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 "encoding/base64" 9 ) 10 11 // Numerical elements 12 const ( 13 CharsetBinaryDigits = "01" 14 CharsetOctalDigits = "01234567" 15 CharsetDecimalDigits = "0123456789" 16 CharsetHexadecimalDigits = "0123456789aAbBcCdDeEfF" 17 CharsetSign = "+-" 18 CharsetPeriod = "." 19 CharsetExponent = "eEp" 20 CharsetAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 21 CharsetAlphaNum = CharsetDecimalDigits + CharsetAlpha 22 CharsetBase64 = CharsetAlphaNum + "+/" 23 24 // StdEncoding is the standard base64 encoding, as defined in 25 // RFC 4648. 26 CharsetBase64StdEncoding = CharsetBase64RawStdEncoding + string(base64.StdPadding) 27 28 // URLEncoding is the alternate base64 encoding defined in RFC 4648. 29 // It is typically used in URLs and file names. 30 CharsetBase64URLEncoding = CharsetBase64RawURLEncoding + string(base64.StdPadding) 31 32 // RawStdEncoding is the standard raw, unpadded base64 encoding, 33 // as defined in RFC 4648 section 3.2. 34 // This is the same as StdEncoding but omits padding characters. 35 CharsetBase64RawStdEncoding = CharsetAlphaNum + "+/" 36 37 // RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648. 38 // It is typically used in URLs and file names. 39 // This is the same as URLEncoding but omits padding characters. 40 CharsetBase64RawURLEncoding = CharsetAlphaNum + "-_" 41 ) 42 43 // take in a character set and a length and will generate a random string using that character set. 44 func StringWithCharset(len int, charset string) string { 45 s, err := StringCryptoWithCharset(int64(len), charset) 46 if err == nil { 47 return s 48 } 49 return StringMathWithCharset(len, charset) 50 } 51 52 // only take in a length, and will use a default characters set to generate a random string 53 func String(len int) string { 54 return StringWithCharset(len, CharsetAlphaNum) 55 }