Created
May 16, 2011 16:34
-
-
Save telamon/974789 to your computer and use it in GitHub Desktop.
Really short(6chars) hash method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Really short hash, (no extra collisions besides the known CRC32 ) | |
# Correct term for this encoding should be "Trimmed Urlsafe Base Encoded CRC32 Hash" or TUBECH?.. two-bitch encoding, lol. | |
# String.send(:include , ShortHash) | |
# "Hello World".short_hash # => "VrEXSg" | |
module ShortHash | |
require 'base64' | |
def ShortHash::base64_hash(str) | |
# doing gsub('+','-').gsub('/','_') because I could not find Base64.urlsafe_base64 encoding in Ruby 1.8.7 | |
# doing gsub(/==\n?$/,'') to remove unnecessary base64 padding wich will always be '==\n' due to the constant crc32 length. | |
Base64.encode64([str.hash].pack('l')).gsub('+','-').gsub('/','_').gsub(/==\n?$/,'') | |
end | |
def short_hash | |
ShortHash::base64_crc32(self) | |
end | |
def ShortHash::base64_sha1(str) | |
Base64.encode64(Digest::SHA1.digest(str)).gsub('+','-').gsub('/','_').gsub(/=\n?$/,'') | |
end | |
def short_sha | |
ShortHash::base64_sha1(self) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment