module CryptBufferConcern::Padding
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.
Public Instance Methods
pad(n,replace: true)
click to toggle source
pad an existing buffer with the given amount of bytes If a padding already exists, replace: decides whether or not to replace it
# 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
padding()
click to toggle source
Return any existing padding
# 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?()
click to toggle source
# File lib/crypto-toolbox/crypt_buffer/concerns/padding.rb, line 49 def padding? !padding.empty? end
strip_padding()
click to toggle source
Strip the existing padding if present
# 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!()
click to toggle source
# File lib/crypto-toolbox/crypt_buffer/concerns/padding.rb, line 39 def strip_padding! validate_padding! strip_padding end
validate_padding!()
click to toggle source
# 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
Private Instance Methods
subset_padding()
click to toggle source
# File lib/crypto-toolbox/crypt_buffer/concerns/padding.rb, line 66 def subset_padding last = bytes.last return [] if last.nil? return [] if last >= length # e.g. 5: take from -5, 5 elems bytes[-1 * last, last] end