class HexaPDF::Encryption::RubyARC4
See: PDF2.0 s7.6.3
For reference: This implementation is about 250 times slower than the FastARC4 version.
FastARC4 class based on OpenSSL should be used when possible.
Since this algorithm is implemented in pure Ruby, it is not very fast. Therefore the
Pure Ruby implementation of the general encryption algorithm ARC4.
def initialize(key)
def initialize(key) initialize_state(key) @i = @j = 0 end
def initialize_state(key)
def initialize_state(key) i = j = 0 @state = INITIAL_STATE.dup key_length = key.length while i < 256 j = (j + @state[i] + key.getbyte(i % key_length)) % 256 @state[i], @state[j] = @state[j], @state[i] i += 1 end end
def process(data)
Since this is a symmetric algorithm, the same method can be used for encryption and
Processes the given data.
def process(data) result = data.dup.force_encoding(Encoding::BINARY) di = 0 while di < result.length @i = (@i + 1) % 256 @j = (@j + @state[@i]) % 256 @state[@i], @state[@j] = @state[@j], @state[@i] result.setbyte(di, result.getbyte(di) ^ @state[(@state[@i] + @state[@j]) % 256]) di += 1 end result end