Class: Pdfrb::Encryption::AES

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

Overview

AES cipher in CBC mode for PDF V4..V6 (s7.6.3.2 / 7.6.3.3). Backed by openssl stdlib for performance and correctness. Caller derives the per-object key and the 16-byte IV (PDF V5+ uses IV-in-ciphertext; PDF V4 uses random IV per stream).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_size: 128, mode: :CBC) ⇒ AES

Returns a new instance of AES.



14
15
16
17
# File 'lib/pdfrb/encryption/aes.rb', line 14

def initialize(key_size: 128, mode: :CBC)
  @key_size = key_size
  @mode = mode
end

Instance Attribute Details

#key_sizeObject (readonly)

Returns the value of attribute key_size.



12
13
14
# File 'lib/pdfrb/encryption/aes.rb', line 12

def key_size
  @key_size
end

#modeObject (readonly)

Returns the value of attribute mode.



12
13
14
# File 'lib/pdfrb/encryption/aes.rb', line 12

def mode
  @mode
end

Instance Method Details

#decrypt(ciphertext, key) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/pdfrb/encryption/aes.rb', line 28

def decrypt(ciphertext, key)
  cipher = openssl_cipher(:decrypt, key.bytesize)
  iv = ciphertext.byteslice(0, 16)
  body = ciphertext.byteslice(16..)
  cipher.key = key.b
  cipher.iv = iv
  cipher.padding = 0
  decrypted = cipher.update(body) + cipher.final
  strip_pkcs7(decrypted)
end

#encrypt(plain, key, iv) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/pdfrb/encryption/aes.rb', line 19

def encrypt(plain, key, iv)
  cipher = openssl_cipher(:encrypt, key.bytesize)
  cipher.key = key.b
  cipher.iv = iv.b
  cipher.padding = 0 # PDF pads itself (PKCS#7)
  out = cipher.update(pad_pkcs7(plain.b, 16)) + cipher.final
  iv.b + out
end