Sha256: 4f2724f18a23f65a38377a910caba47762103554bb727f3d3b15a851a05c8f52

Contents?: true

Size: 1.05 KB

Versions: 7

Compression:

Stored size: 1.05 KB

Contents

require 'openssl'
require 'base64'

module Nexus
  class Cipher

    def initialize(pass, token = nil)
      @token = Base64.strict_decode64(token) if token
      @token ||= OpenSSL::Random.random_bytes(32)

      iter = 20_000
      key_len = 32
      @key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(pass,
                                             @token,
                                             iter,
                                             key_len)
    end

    def cipher
      @cipher ||= OpenSSL::Cipher.new('aes-256-cbc')
    end

    private :cipher

    def token
      Base64.strict_encode64(@token)
    end

    def iv
      Base64.strict_encode64(@iv) if @iv
    end

    def iv=(iv)
      @iv = Base64.strict_decode64(iv)
    end

    def encrypt(data)
      c = cipher
      c.encrypt
      c.key = @key
      @iv = c.random_iv
      Base64.strict_encode64(c.update(data) + c.final)
    end

    def decrypt(data)
      c = cipher
      c.decrypt
      c.key = @key
      c.iv = @iv
      c.update(Base64.strict_decode64(data)) + c.final
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
nexus-debug-1.4.6 lib/nexus/cipher.rb
nexus-debug-1.4.5 lib/nexus/cipher.rb
nexus-debug-1.4.4 lib/nexus/cipher.rb
nexus-debug-1.4.3 lib/nexus/cipher.rb
nexus-debug-1.4.2 lib/nexus/cipher.rb
nexus-debug-1.4.1 lib/nexus/cipher.rb
nexus-debug-1.4.0 lib/nexus/cipher.rb