Class: Obfuscate::Crypt

Inherits:
Object
  • Object
show all
Defined in:
lib/obfuscate/crypt.rb

Constant Summary collapse

Base64Error =
Class.new(StandardError)
UnsupportedModeError =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Crypt

New instance of Obfuscate::Crypt



30
31
32
33
# File 'lib/obfuscate/crypt.rb', line 30

def initialize(config)
  @crypt = Crypt::Blowfish.new( config.salt )
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



24
25
26
# File 'lib/obfuscate/crypt.rb', line 24

def config
  @config
end

#exec_configObject (readonly)

Returns the value of attribute exec_config.



25
26
27
# File 'lib/obfuscate/crypt.rb', line 25

def exec_config
  @exec_config
end

Instance Method Details

#clarify(text, override_mode = nil) ⇒ String

Clarify text



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/obfuscate/crypt.rb', line 64

def clarify(text, override_mode = nil)

  @exec_config = @config.apply(:mode => (override_mode || @config.mode))
  obfuscated = text.to_s

  if @exec_config.encode
    obfuscated << "=" if @exec_config.remove_trailing_equal?
    obfuscated = Base64.urlsafe_decode64(obfuscated)
  end

  begin
    if @exec_config.mode == :string
      @crypt.decrypt_string(obfuscated)
    elsif @exec_config.mode == :block
      @crypt.decrypt_block(obfuscated).strip
    else
      raise UnsupportedModeError.new("Unknown mode: #{@exec_config.mode}")
    end
  rescue ArgumentError => ex
    raise Base64Error.new("Cannot decode #{text}") if ex.message == 'invalid base64'

    raise ex
  rescue => ex
    raise Base64Error.new("Cannot decode #{text}") if ex.message == "undefined method `%'"

    raise ex
  end
end

#obfuscate(text, override_mode = nil) ⇒ String

Obfuscate text



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/obfuscate/crypt.rb', line 39

def obfuscate(text, override_mode = nil)

  @exec_config = @config.apply(:mode => (override_mode || @config.mode) )

  obfuscated = nil
  if @exec_config.mode == :string
    obfuscated = @crypt.encrypt_string(text)
  elsif @exec_config.mode == :block
    obfuscated = @crypt.encrypt_block(text.to_s.ljust(8))
  else
    raise "Unsupport Mode"
  end

  if @exec_config.encode
    obfuscated = Base64.urlsafe_encode64(obfuscated).strip
    obfuscated = obfuscated.chomp("=") if @exec_config.remove_trailing_equal?
  end

  obfuscated
end