Skip to content

Instantly share code, notes, and snippets.

@charlie-wasp
Created August 15, 2018 15:00
Show Gist options
  • Save charlie-wasp/433588e8f4f7e00fc639a79332ad676f to your computer and use it in GitHub Desktop.
Save charlie-wasp/433588e8f4f7e00fc639a79332ad676f to your computer and use it in GitHub Desktop.
Obfuscated ID generator
module ObfuscatedId
extend ActiveSupport::Concern
# Constants used to obfuscate identifiers with formula id * multipier % modulo
# modulo and multiplier must be coprime numbers to avoid collisions
# modulo must be larger than maximum value of id
MODULO = Rails.application.secrets.id_obfuscation[:modulo]
EXPONENT = Rails.application.secrets.id_obfuscation[:exponent]
# Should contain digits and letters common for latin and cyrillic alphabets
# "12345679AEKMHPCTYX".split('').shuffle.join
MAPPING = Rails.application.secrets.id_obfuscation[:mapping].freeze
# @param input [Integer]
def generate_obfuscated_id(number)
obfuscated_id = EXPONENT * number % MODULO
encode_obfuscated_to_string(obfuscated_id)
end
private
def encode_obfuscated_to_string(number)
base = MAPPING.size
result = []
current = number
loop do
break if current.zero?
current, modulo = current.divmod(base)
result << MAPPING[modulo]
end
result.in_groups_of(4).map(&:join).join("-")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment