Skip to content
GitLab
Explore
Sign in
Register
Primary navigation
Search or go to…
Project
Authenticated App
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Service Desk
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
GitLab community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Calyx Institute
Ruby Gems
Authenticated App
Commits
aee8e4bc
Commit
aee8e4bc
authored
Feb 10, 2023
by
ziggy
Committed by
ziggy
Feb 10, 2023
Browse files
Options
Downloads
Patches
Plain Diff
add RandomCode
parent
ae870486
No related branches found
No related tags found
No related merge requests found
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
lib/random_code.rb
+49
-0
49 additions, 0 deletions
lib/random_code.rb
with
49 additions
and
0 deletions
lib/random_code.rb
0 → 100644
+
49
−
0
View file @
aee8e4bc
require
'securerandom'
#
#
# Generates a random code in which there are no ambiguous characters.
# This way, no one has to puzzle if that is an 'l' or a '1'.
#
# With only lowercase and no ambiguous characters, the entropy of strings
# generated with RandomCode is lower than a string with capital letters
# and confusing characters. To compensate, you should pick a longer string.
#
# Entropy is:
#
# possible_chars = 32
# Math.log(length**possible_chars, 2)
#
# length 8 => 96 bits
# length 9 => 101 bits
# length 10 => 106 bits
# length 11 => 110 bits
# length 12 => 114 bits
# length 13 => 118 bits
# length 14 => 121 bits
# length 15 => 125 bits
# length 16 => 128 bits
# length 17 => 130 bits
# length 18 => 133 bits
# length 19 => 135 bits
# length 20 => 138 bits
#
module
RandomCode
POSSIBLE
=
%w[a b c d e f g h i j k m n p q r s t u v w x y z 2 3 4 5 6 7 8 9]
def
self
.
entropy
(
length
)
Math
.
log
(
length
**
POSSIBLE
.
length
,
2
).
truncate
end
def
self
.
create
(
length
,
split
=
nil
)
possible
=
POSSIBLE
.
shuffle
str
=
SecureRandom
.
random_bytes
(
length
).
each_byte
.
map
{
|
byte
|
possible
[
byte
%
possible
.
length
]
}.
join
if
split
return
str
.
scan
(
/.{
#{
split
}
}/
).
join
(
'-'
)
else
return
str
end
end
end
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment