podman

Форк
0
/
cryptorandomstringutils.go 
230 строк · 7.3 Кб
1
/*
2
Copyright 2014 Alexander Okoli
3

4
Licensed under the Apache License, Version 2.0 (the "License");
5
you may not use this file except in compliance with the License.
6
You may obtain a copy of the License at
7

8
    http://www.apache.org/licenses/LICENSE-2.0
9

10
Unless required by applicable law or agreed to in writing, software
11
distributed under the License is distributed on an "AS IS" BASIS,
12
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16

17
package goutils
18

19
import (
20
	"crypto/rand"
21
	"fmt"
22
	"math"
23
	"math/big"
24
	"unicode"
25
)
26

27
/*
28
CryptoRandomNonAlphaNumeric creates a random string whose length is the number of characters specified.
29
Characters will be chosen from the set of all characters (ASCII/Unicode values between 0 to 2,147,483,647 (math.MaxInt32)).
30

31
Parameter:
32
	count - the length of random string to create
33

34
Returns:
35
	string - the random string
36
	error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...)
37
*/
38
func CryptoRandomNonAlphaNumeric(count int) (string, error) {
39
	return CryptoRandomAlphaNumericCustom(count, false, false)
40
}
41

42
/*
43
CryptoRandomAscii creates a random string whose length is the number of characters specified.
44
Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive).
45

46
Parameter:
47
	count - the length of random string to create
48

49
Returns:
50
	string - the random string
51
	error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...)
52
*/
53
func CryptoRandomAscii(count int) (string, error) {
54
	return CryptoRandom(count, 32, 127, false, false)
55
}
56

57
/*
58
CryptoRandomNumeric creates a random string whose length is the number of characters specified.
59
Characters will be chosen from the set of numeric characters.
60

61
Parameter:
62
	count - the length of random string to create
63

64
Returns:
65
	string - the random string
66
	error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...)
67
*/
68
func CryptoRandomNumeric(count int) (string, error) {
69
	return CryptoRandom(count, 0, 0, false, true)
70
}
71

72
/*
73
CryptoRandomAlphabetic creates a random string whose length is the number of characters specified.
74
Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
75

76
Parameters:
77
	count - the length of random string to create
78
	letters - if true, generated string may include alphabetic characters
79
	numbers - if true, generated string may include numeric characters
80

81
Returns:
82
	string - the random string
83
	error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...)
84
*/
85
func CryptoRandomAlphabetic(count int) (string, error) {
86
	return CryptoRandom(count, 0, 0, true, false)
87
}
88

89
/*
90
CryptoRandomAlphaNumeric creates a random string whose length is the number of characters specified.
91
Characters will be chosen from the set of alpha-numeric characters.
92

93
Parameter:
94
	count - the length of random string to create
95

96
Returns:
97
	string - the random string
98
	error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...)
99
*/
100
func CryptoRandomAlphaNumeric(count int) (string, error) {
101
	return CryptoRandom(count, 0, 0, true, true)
102
}
103

104
/*
105
CryptoRandomAlphaNumericCustom creates a random string whose length is the number of characters specified.
106
Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
107

108
Parameters:
109
	count - the length of random string to create
110
	letters - if true, generated string may include alphabetic characters
111
	numbers - if true, generated string may include numeric characters
112

113
Returns:
114
	string - the random string
115
	error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...)
116
*/
117
func CryptoRandomAlphaNumericCustom(count int, letters bool, numbers bool) (string, error) {
118
	return CryptoRandom(count, 0, 0, letters, numbers)
119
}
120

121
/*
122
CryptoRandom creates a random string based on a variety of options, using using golang's crypto/rand source of randomness.
123
If the parameters start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used,
124
unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32, respectively.
125
If chars is not nil, characters stored in chars that are between start and end are chosen.
126

127
Parameters:
128
	count - the length of random string to create
129
	start - the position in set of chars (ASCII/Unicode int) to start at
130
	end - the position in set of chars (ASCII/Unicode int) to end before
131
	letters - if true, generated string may include alphabetic characters
132
	numbers - if true, generated string may include numeric characters
133
	chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars.
134

135
Returns:
136
	string - the random string
137
	error - an error stemming from invalid parameters: if count < 0; or the provided chars array is empty; or end <= start; or end > len(chars)
138
*/
139
func CryptoRandom(count int, start int, end int, letters bool, numbers bool, chars ...rune) (string, error) {
140
	if count == 0 {
141
		return "", nil
142
	} else if count < 0 {
143
		err := fmt.Errorf("randomstringutils illegal argument: Requested random string length %v is less than 0.", count) // equiv to err := errors.New("...")
144
		return "", err
145
	}
146
	if chars != nil && len(chars) == 0 {
147
		err := fmt.Errorf("randomstringutils illegal argument: The chars array must not be empty")
148
		return "", err
149
	}
150

151
	if start == 0 && end == 0 {
152
		if chars != nil {
153
			end = len(chars)
154
		} else {
155
			if !letters && !numbers {
156
				end = math.MaxInt32
157
			} else {
158
				end = 'z' + 1
159
				start = ' '
160
			}
161
		}
162
	} else {
163
		if end <= start {
164
			err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) must be greater than start (%v)", end, start)
165
			return "", err
166
		}
167

168
		if chars != nil && end > len(chars) {
169
			err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) cannot be greater than len(chars) (%v)", end, len(chars))
170
			return "", err
171
		}
172
	}
173

174
	buffer := make([]rune, count)
175
	gap := end - start
176

177
	// high-surrogates range, (\uD800-\uDBFF) = 55296 - 56319
178
	//  low-surrogates range, (\uDC00-\uDFFF) = 56320 - 57343
179

180
	for count != 0 {
181
		count--
182
		var ch rune
183
		if chars == nil {
184
			ch = rune(getCryptoRandomInt(gap) + int64(start))
185
		} else {
186
			ch = chars[getCryptoRandomInt(gap)+int64(start)]
187
		}
188

189
		if letters && unicode.IsLetter(ch) || numbers && unicode.IsDigit(ch) || !letters && !numbers {
190
			if ch >= 56320 && ch <= 57343 { // low surrogate range
191
				if count == 0 {
192
					count++
193
				} else {
194
					// Insert low surrogate
195
					buffer[count] = ch
196
					count--
197
					// Insert high surrogate
198
					buffer[count] = rune(55296 + getCryptoRandomInt(128))
199
				}
200
			} else if ch >= 55296 && ch <= 56191 { // High surrogates range (Partial)
201
				if count == 0 {
202
					count++
203
				} else {
204
					// Insert low surrogate
205
					buffer[count] = rune(56320 + getCryptoRandomInt(128))
206
					count--
207
					// Insert high surrogate
208
					buffer[count] = ch
209
				}
210
			} else if ch >= 56192 && ch <= 56319 {
211
				// private high surrogate, skip it
212
				count++
213
			} else {
214
				// not one of the surrogates*
215
				buffer[count] = ch
216
			}
217
		} else {
218
			count++
219
		}
220
	}
221
	return string(buffer), nil
222
}
223

224
func getCryptoRandomInt(count int) int64 {
225
	nBig, err := rand.Int(rand.Reader, big.NewInt(int64(count)))
226
	if err != nil {
227
		panic(err)
228
	}
229
	return nBig.Int64()
230
}
231

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.