Class: PDF::Writer::ARC4

Inherits:
Object show all
Defined in:
lib/extensions/pdf-writer/pdf/writer/arc4.rb

Overview

ARC4 methods A series of function to implement ARC4 encoding in Ruby

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ ARC4

Initializes the ARC4 encryption with the specified key.



17
18
19
# File 'lib/extensions/pdf-writer/pdf/writer/arc4.rb', line 17

def initialize(key)
  @key = key
end

Instance Method Details

#encrypt(text) ⇒ Object

ARC4 encrypt a text string



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/extensions/pdf-writer/pdf/writer/arc4.rb', line 48

def encrypt(text)
  len = text.size
  a = b = 0
  c = @arc4.dup
  out = ""

  text.each_byte do |x|
    a = (a + 1) % 256
    b = (b + c[a].to_i) % 256
    c[a], c[b] = c[b], c[a]
    k = (c[(c[a].to_i + c[b].to_i) % 256]).to_i
    out << ("%c" % (x.to_i ^ k))
  end
  out
end

#init(key) ⇒ Object

Initialize the ARC4 encryption.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/extensions/pdf-writer/pdf/writer/arc4.rb', line 28

def init(key)
  @arc4 = ""

    # Setup the control array
  return if key.empty?

  a = []
  (0..255).each { |ii| a[ii] = "%c" % ii }

  k = (key * 256)[0..255].split(//)

  jj = 0
  @arc4.each_with_index do |el, ii|
    jj = ((jj + el.to_i) + k[ii].to_i) % 256
    a[ii], a[jj] = a[jj], a[ii]
  end
  @arc4 = a.join
end

#prepare(object) ⇒ Object

Initialize the encryption for processing a particular object.



22
23
24
25
# File 'lib/extensions/pdf-writer/pdf/writer/arc4.rb', line 22

def prepare(object)
  hex = ("%06x" % [object.oid]).scan(/../).reverse
  init(Digest::MD5.digest("#{@key}#{hex.pack('H10')}")[0...10])
end