Module: CryptBufferConcern::Padding

Included in:
CryptBuffer
Defined in:
lib/crypto-toolbox/crypt_buffer/concerns/padding.rb

Overview

This module extends functionality the CryptBuffer to handle PKCS7 padding. It has the ability to detect, replace, add and strip a padding from a CryptBuffer to return a new one without mutating the existing buffer.

The purpose is making crypto analysis of cbc and other cipher modes that use pkcs7 padding easier.

Defined Under Namespace

Classes: InvalidPkcs7Padding

Instance Method Summary collapse

Instance Method Details

#pad(n, replace: true) ⇒ Object

pad an existing buffer with the given amount of bytes If a padding already exists, replace: decides whether or not to replace it



56
57
58
59
60
61
62
63
# File 'lib/crypto-toolbox/crypt_buffer/concerns/padding.rb', line 56

def pad(n,replace: true)
  if padding? && replace
      strip_padding.pad(n)
  else
    pad = [n] * n
    return CryptBuffer(bytes + pad )
  end
end

#paddingObject

Return any existing padding



16
17
18
19
20
21
22
23
24
25
# File 'lib/crypto-toolbox/crypt_buffer/concerns/padding.rb', line 16

def padding
  last   = bytes.last
  subset = subset_padding

  if subset.all?{|e| e == last }
    self.class.new(subset)
  else
    self.class.new([])
  end
end

#padding?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/crypto-toolbox/crypt_buffer/concerns/padding.rb', line 49

def padding?
  !padding.empty?
end

#strip_paddingObject

Strip the existing padding if present



28
29
30
31
32
33
34
35
36
37
# File 'lib/crypto-toolbox/crypt_buffer/concerns/padding.rb', line 28

def strip_padding
  subset = bytes
  
  if padding?
    pad = padding
    len = pad.length
    subset = bytes[0,bytes.length - len]
  end
  self.class.new(subset)
end

#strip_padding!Object



39
40
41
42
# File 'lib/crypto-toolbox/crypt_buffer/concerns/padding.rb', line 39

def strip_padding!
  validate_padding! 
  strip_padding
end

#validate_padding!Object



44
45
46
47
# File 'lib/crypto-toolbox/crypt_buffer/concerns/padding.rb', line 44

def validate_padding!
  raise InvalidPkcs7Padding, "No valid pkcs#7 padding present" unless padding?
  true
end