Sha256: 47a96c134558da375d6f685a9360d85e4a584288542fa925977b530626b24d10

Contents?: true

Size: 1.33 KB

Versions: 71

Compression:

Stored size: 1.33 KB

Contents

# encoding: UTF-8
require 'securerandom'
require 'digest/sha2'
require 'openssl'
require 'base64'

module Kafo
  class PasswordManager
    # generate a random password of lenght n
    #
    # on ruby >= 1.9 we use builtin method urlsafe_base64, on olders we use our own
    # implementation (inspired by urlsafe_base64)
    #
    # the result may contain A-Z, a-z, 0-9, “-” and “_”. “=”
    def password(n = 32)
      return SecureRandom.urlsafe_base64(n) if SecureRandom.respond_to?(:urlsafe_base64)

      s = [SecureRandom.random_bytes(n)].pack("m*")
      s.delete!("\n")
      s.tr!("+/", "-_")
      s.delete!("=")
      s
    end

    def aes_encrypt(text, passphrase)
      cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
      cipher.encrypt
      cipher.key = Digest::SHA2.hexdigest(passphrase)
      cipher.iv  = Digest::SHA2.hexdigest(passphrase + passphrase)

      encrypted = cipher.update(text)
      encrypted << cipher.final
      Base64.encode64(encrypted)
    end

    def aes_decrypt(text, passphrase)
      cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
      cipher.decrypt
      cipher.key = Digest::SHA2.hexdigest(passphrase)
      cipher.iv  = Digest::SHA2.hexdigest(passphrase + passphrase)

      decrypted = cipher.update(Base64.decode64(text))
      decrypted << cipher.final
      decrypted
    end
  end
end

Version data entries

71 entries across 71 versions & 1 rubygems

Version Path
kafo-3.0.0 lib/kafo/password_manager.rb
kafo-2.1.0 lib/kafo/password_manager.rb
kafo-2.0.2 lib/kafo/password_manager.rb
kafo-2.0.1 lib/kafo/password_manager.rb
kafo-2.0.0 lib/kafo/password_manager.rb
kafo-1.0.8 lib/kafo/password_manager.rb
kafo-1.0.7 lib/kafo/password_manager.rb
kafo-1.0.6 lib/kafo/password_manager.rb
kafo-1.0.5 lib/kafo/password_manager.rb
kafo-1.0.4 lib/kafo/password_manager.rb
kafo-0.9.8 lib/kafo/password_manager.rb
kafo-1.0.3 lib/kafo/password_manager.rb
kafo-0.9.7 lib/kafo/password_manager.rb
kafo-1.0.2 lib/kafo/password_manager.rb
kafo-1.0.1 lib/kafo/password_manager.rb
kafo-1.0.0 lib/kafo/password_manager.rb
kafo-0.9.6 lib/kafo/password_manager.rb
kafo-0.9.5 lib/kafo/password_manager.rb
kafo-0.9.4 lib/kafo/password_manager.rb
kafo-0.9.3 lib/kafo/password_manager.rb