Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Slug
CIPHER = 'RC2'.freeze
def initialize(key, iv)
@key = key
@iv = self.class.hex_to_bytes(iv)
end
def self.generate_iv
bytes_to_hex(OpenSSL::Cipher.new(CIPHER).random_iv)
end
def encrypt(id)
c = cipher
c.encrypt
id = id.to_s(36)
s = c.update(id) + c.final
self.class.bytes_to_hex(s)
end
def decrypt(encrypted)
c = cipher
c.decrypt
s = self.class.hex_to_bytes(encrypted)
(c.update(s) + c.final).to_i(36)
end
private
def cipher
cipher = OpenSSL::Cipher.new(CIPHER)
cipher.iv = @iv
cipher.key = @key
cipher
end
def self.bytes_to_hex(byte_string)
byte_string.unpack('H*')[0].upcase
end
def self.hex_to_bytes(hex_string)
[hex_string].pack("H*").unpack("C*").pack("c*")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.