Class: Shugoi::Obfuscator

Inherits:
Object
  • Object
show all
Defined in:
lib/shugoi/obfuscator.rb

Instance Method Summary collapse

Instance Method Details

#apply(code, seed) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/shugoi/obfuscator.rb', line 7

def apply(code, seed)
  key = Digest::SHA256.hexdigest("#{seed}sg_val_v1")[0, 32].scan(/../).map { |b| b.to_i(16) }
  encoded = code.gsub(/(['"])(.*?)(?<!\\)\1/m) do
    value = Regexp.last_match(2).gsub(/\\(['"\\])/, '\\1')
    bytes = value.encode("UTF-8").bytes.each_with_index.map { |b, i| format("%02x", b ^ key[i % key.length]) }.join
    "_D(\"#{bytes}\")"
  end.gsub(%r{^\s*//.*$}, "").gsub(%r{/\*[\s\S]*?\*/}, "").gsub(/\n{3,}/, "\n\n")
  encoded_key = key.pack("C*").bytes.map { |b| format('\\x%02x', b) }.join
  decoder = <<~JS.delete("\n")
    var _D=function(h){var k="#{encoded_key}",r="";for(var i=0;i<h.length;i+=2){r+=String.fromCharCode(parseInt(h.substr(i,2),16)^k.charCodeAt((i/2)%#{key.length}))}return r};
  JS
  (decoder + encoded).gsub(%r{</(script|style)}i, '<\\/\\1')
end