Skip to content

Instantly share code, notes, and snippets.

@thomaswitt
Last active January 4, 2016 06:09
Show Gist options
  • Select an option

  • Save thomaswitt/8579559 to your computer and use it in GitHub Desktop.

Select an option

Save thomaswitt/8579559 to your computer and use it in GitHub Desktop.
Crypt Helper
require 'rubygems'
require 'openssl'
require 'digest/sha2'
require 'base64'
class CryptHelper
def self.generate_rsa_key(passphrase, bits = 4096)
cipher = OpenSSL::Cipher::AES256.new(:CBC)
rsa_key = OpenSSL::PKey::RSA.generate(bits)
rsa_key.to_pem(cipher, passphrase)
end
def self.decrypt_rsa_key(encrypted_master_rsa_key_pem, passphrase)
OpenSSL::PKey::RSA.new(encrypted_master_rsa_key_pem, passphrase)
end
def self.generate_iv64
cipher = OpenSSL::Cipher::AES256.new(:CBC)
Base64.strict_encode64(cipher.random_iv)
end
def self.encrypt64(string, pass, iv_b64)
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt
cipher.key = Digest::SHA512.digest(pass)
cipher.iv = Base64.strict_decode64(iv_b64)
encrypted = cipher.update(string) + cipher.final
Base64.strict_encode64(encrypted)
end
def self.decrypt64(string_b64, pass, iv_b64)
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.decrypt
cipher.key = Digest::SHA512.digest(pass)
cipher.iv = Base64.strict_decode64(iv_b64)
cipher.update(Base64.strict_decode64(string_b64)) + cipher.final
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment