Skip to content

Instantly share code, notes, and snippets.

@iufuenza
Last active January 28, 2023 04:28
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iufuenza/183a45c601a5c157a5372c5f1cfb9e3e to your computer and use it in GitHub Desktop.
Save iufuenza/183a45c601a5c157a5372c5f1cfb9e3e 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)
    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
    decrypted = cipher.update(input_word)
    decrypted << cipher.final
  end

Documentation: https://ruby-doc.org/stdlib-2.0.0/libdoc/openssl/rdoc/OpenSSL.html

  • Message Encryptor
  def self.encrypt(input_word)
    crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base)
    crypt.encrypt_and_sign(input_word)
  end

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

Documentation: http://api.rubyonrails.org/classes/ActiveSupport/MessageEncryptor.html

  • Base64
  def self.encrypt(input_word)
    Base64.encode64(input_word)
  end

  def self.decrypt(input_word)
    Base64.decode64(input_word)
  end

Documentation: https://ruby-doc.org/stdlib-2.1.3/libdoc/base64/rdoc/Base64.html

One way encryption

  • Crypt
  def self.encrypt(input_word, key)
    key.crypt(input_word)
  end

Documentation: https://apidock.com/ruby/String/crypt

Gems

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