Skip to content

Instantly share code, notes, and snippets.

@iufuenza
Created April 17, 2017 22:36
Show Gist options
  • Save iufuenza/3524fbb5c1f610fc532ba1b73961a09b to your computer and use it in GitHub Desktop.
Save iufuenza/3524fbb5c1f610fc532ba1b73961a09b to your computer and use it in GitHub Desktop.

Encryptions methods using Ruby

In this gist I'll show you how to encrypt messages using Ruby built-in and external libraries. Whenever possible I'll show you how to define in the most simplest way the encryption and the decryption methods.

Two way encryption

  • Openssl
  def self.encrypt(input_word)
    key = 'secret'
    cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC').encrypt
    cipher.key = Digest::SHA1.hexdigest key
    cipher.update(input_word) + cipher.final
  end

  def self.decrypt(input_word)
    key = 'secret'
    cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC').decrypt
    cipher.key = Digest::SHA1.hexdigest key
    cipher.update(input_word) + cipher.final
  end
  • Message Encryptor
  def encrypt(input_word)
    crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base)
    crypt.encrypt_and_sign(input_word)
  end

  def decrypt(input_word)
    crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base)
    crypt.decrypt_and_verify(input_word)
  end
  • Base64

One way encryption

Gems

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment