Skip to content

Instantly share code, notes, and snippets.

@Merovex
Created August 9, 2024 09:45
Show Gist options
  • Save Merovex/2d0b1634f7f08767a3c21345c5d71170 to your computer and use it in GitHub Desktop.
Save Merovex/2d0b1634f7f08767a3c21345c5d71170 to your computer and use it in GitHub Desktop.
Takes a number (like an id) and one-way encrypts to a slug (needs to be stored in database)
require 'digest'
SLUG_DEFAULT = 4
SAFESTRING = "BDFGHJKLMNPQRTVWXYZbdfghjkmnpqrtvwxyz26789".freeze
def encrypt_to_slug(number, size: SLUG_DEFAULT, alphabet: SAFESTRING)
non_numeric_set = alphabet.gsub(/[0-9]/, '') # Characters without digits
# Step 1: Hash the number (using SHA256)
hash = Digest::SHA256.digest(number.to_s)
# Step 2: Convert hash to an integer
num = hash.unpack1("H*").to_i(16)
# Step 3: Encode to a custom base string
base = alphabet.length
result = ''
while num > 0
result = alphabet[num % base] + result
num /= base
end
encoded = result.rjust(size, alphabet[0])[0,size] # Ensure it's the correct size
# Step 4: Ensure the first character is non-numeric
encoded[0] = non_numeric_set[num % non_numeric_set.length] unless non_numeric_set.include?(encoded[0])
encoded
end
# Example usage: Generate and format output into a Markdown table with 5 columns
output = "| " # Start the first row of the Markdown table
1000.times do |i|
encoded_string = encrypt_to_slug(i, size: 4, alphabet: SAFESTRING)
output += "#{encoded_string} | "
output += "\n| " if (i + 1) % 5 == 0 # Start a new row after every 5 items
end
# Output the result
puts output.strip # Print the output, removing any trailing whitespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment