Last active
April 7, 2017 19:22
-
-
Save iobaixas/da372dbdd60f3538e6c19a58baa99b7b to your computer and use it in GitHub Desktop.
Ejemplos de usos comunes de encriptación
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support/all' | |
require 'digest' | |
require 'securerandom' | |
require 'openssl' | |
module Crypto | |
extend self | |
# Encriptación de un password para guardar en una BD. Usa un salt para evitar ataques con tablas de lookup. | |
def hash_salado(_password) | |
salt = SecureRandom.hex(32) | |
hash = Digest::SHA1.hexdigest(_password + salt) | |
[hash, salt] | |
end | |
# Verificar un password generado usando la funcin 'hash_salado' | |
def verificar_password(_hash_salado, _password) | |
_hash_salado[0] == Digest::SHA1.hexdigest(_password + _hash_salado[1]) | |
end | |
# Implementación básica de TOTP (Time based One Time Password). | |
def calcular_totp(_secreto) | |
time_counter = (Time.now.to_i / 20.seconds).floor | |
hash = OpenSSL::HMAC.digest("SHA256", _secreto, time_counter.to_s) # usa SHA256 varias veces | |
first_int = hash[0..4].unpack("N").first | |
first_int % 10000 | |
end | |
# Implementación básica de encriptación parecida a la utilizada en Cookies, el secreto | |
def encriptar_galleta(_galleta, _secreto) | |
cipher = OpenSSL::Cipher.new('AES-256-CBC') | |
cipher.encrypt | |
cipher.key = Base64.decode64 _secreto | |
iv = cipher.random_iv | |
galleta_json = _galleta.to_json | |
Base64.encode64(cipher.update(galleta_json) + cipher.final + iv) | |
end | |
# Desencriptar galleta generada en la función `encriptar_galleta`. | |
def desencriptar_galleta(_galleta_molida, _secreto) | |
galleta_binaria = Base64.decode64(_galleta_molida) | |
cipher = OpenSSL::Cipher.new('AES-256-CBC') | |
cipher.decrypt | |
cipher.key = Base64.decode64 _secreto | |
cipher.iv = galleta_binaria[-16..-1] | |
JSON.load(cipher.update(galleta_binaria[0...-16]) + cipher.final) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment