Class: Pdfrb::Encryption::RC4Impl

Inherits:
Object
  • Object
show all
Defined in:
lib/pdfrb/encryption/standard_security_handler.rb

Overview

Minimal RC4 implementation

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ RC4Impl

Returns a new instance of RC4Impl.



167
168
169
170
171
172
173
174
175
# File 'lib/pdfrb/encryption/standard_security_handler.rb', line 167

def initialize(key)
  @s = (0..255).to_a
  j = 0
  key.bytes.each_with_index do |_b, i|
    j = (j + @s[i] + key.getbyte(i % key.bytesize)) & 0xFF
    @s[i], @s[j] = @s[j], @s[i]
  end
  @i = @j = 0
end

Instance Method Details

#process(data, _xor = nil) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
# File 'lib/pdfrb/encryption/standard_security_handler.rb', line 177

def process(data, _xor = nil)
  result = data.dup.force_encoding(Encoding::BINARY)
  result.bytes.each_with_index do |_b, idx|
    @i = (@i + 1) & 0xFF
    @j = (@j + @s[@i]) & 0xFF
    @s[@i], @s[@j] = @s[@j], @s[@i]
    k = @s[(@s[@i] + @s[@j]) & 0xFF]
    result.setbyte(idx, result.getbyte(idx) ^ k)
  end
  result
end