Class: Pdfrb::Encryption::RC4

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

Overview

Pure-Ruby RC4 stream cipher (s7.6.3.1, Algorithm 1). Key can be 1..256 bytes (PDF uses 5..32). Stateless per call: build a new cipher for each (key, oid, gen) tuple.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ RC4

Returns a new instance of RC4.



11
12
13
14
15
16
# File 'lib/pdfrb/encryption/rc4.rb', line 11

def initialize(key)
  @key = key.b
  @s = (0..255).to_a
  @i = @j = 0
  key_schedule
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



9
10
11
# File 'lib/pdfrb/encryption/rc4.rb', line 9

def key
  @key
end

Instance Method Details

#process(bytes) ⇒ Object Also known as: encrypt, decrypt

Encrypt/decrypt bytes (symmetric). Caller is responsible for prepending the per-object key (5..16 bytes derived via MD5 of file_key + oid + gen).



21
22
23
24
25
26
27
28
29
30
# File 'lib/pdfrb/encryption/rc4.rb', line 21

def process(bytes)
  out = +""
  bytes.b.each_byte do |b|
    @i = (@i + 1) & 0xFF
    @j = (@j + @s[@i]) & 0xFF
    @s[@i], @s[@j] = @s[@j], @s[@i]
    out << (b ^ @s[(@s[@i] + @s[@j]) & 0xFF]).chr
  end
  out.force_encoding(Encoding::BINARY)
end