Skip to content

Instantly share code, notes, and snippets.

@snmmaurya
Last active September 26, 2019 20:36
Show Gist options
  • Save snmmaurya/f49dbf1f4d2ba5ced1ff302a2e8ade90 to your computer and use it in GitHub Desktop.
Save snmmaurya/f49dbf1f4d2ba5ced1ff302a2e8ade90 to your computer and use it in GitHub Desktop.
rails simple cryptography to encode and decode a payload based on OpenSSL::Cipher

A simple cryptography to encode and decode a payload based on OpenSSL::Cipher

class SimpleCryptography
  SECRET = "secretkey"

  def self.encode payload
    cipher = OpenSSL::Cipher.new('AES-128-CBC').encrypt
    cipher.key = Digest::SHA1.hexdigest(SECRET).unpack('B16').first
    s = cipher.update(payload) + cipher.final
    s.unpack('H*')[0].upcase
  end

  def self.decode enrypted_payload
    cipher = OpenSSL::Cipher.new('AES-128-CBC').decrypt
    cipher.key = Digest::SHA1.hexdigest(SECRET).unpack('B16').first
    s = [payload].pack("H*").unpack("C*").pack("c*")
    cipher.update(s) + cipher.final
  end
end

Example

payload = "1234567890"

# encode
enrypted_payload = SimpleCryptography.encode(payload)

# decode
decrypted_payload = SimpleCryptography.decode(enrypted_payload)

# compare the decoded payload with actual payload
decrypted_payload == payload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment