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.
- 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
- Crypt
def self.encrypt(input_word, key)
key.crypt(input_word)
end
Documentation: https://apidock.com/ruby/String/crypt
- Encryptor https://github.com/attr-encrypted/encryptor
- Symmetric-encryption https://github.com/rocketjob/symmetric-encryption
- Gibberish https://github.com/mdp/gibberish