Sha256: ec2c44ed133f2293ece4facd9da784f51abaf379624b291b1529d8ac61a153cf

Contents?: true

Size: 1.22 KB

Versions: 36

Compression:

Stored size: 1.22 KB

Contents

module Lockbox
  module Padding
    PAD_FIRST_BYTE = "\x80".b
    PAD_ZERO_BYTE = "\x00".b

    def pad(str, **options)
      pad!(str.dup, **options)
    end

    def unpad(str, **options)
      unpad!(str.dup, **options)
    end

    # ISO/IEC 7816-4
    # same as Libsodium
    # https://libsodium.gitbook.io/doc/padding
    # apply prior to encryption
    # note: current implementation does not
    # try to minimize side channels
    def pad!(str, size: 16)
      raise ArgumentError, "Invalid size" if size < 1

      str.force_encoding(Encoding::BINARY)

      pad_length = size - 1
      pad_length -= str.bytesize % size

      str << PAD_FIRST_BYTE
      pad_length.times do
        str << PAD_ZERO_BYTE
      end

      str
    end

    # note: current implementation does not
    # try to minimize side channels
    def unpad!(str, size: 16)
      raise ArgumentError, "Invalid size" if size < 1

      str.force_encoding(Encoding::BINARY)

      i = 1
      while i <= size
        case str[-i]
        when PAD_ZERO_BYTE
          i += 1
        when PAD_FIRST_BYTE
          str.slice!(-i..-1)
          return str
        else
          break
        end
      end

      raise Lockbox::PaddingError, "Invalid padding"
    end
  end
end

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
lockbox-0.6.0 lib/lockbox/padding.rb
lockbox-0.5.0 lib/lockbox/padding.rb
lockbox-0.4.9 lib/lockbox/padding.rb
lockbox-0.4.8 lib/lockbox/padding.rb
lockbox-0.4.7 lib/lockbox/padding.rb
lockbox-0.4.6 lib/lockbox/padding.rb
lockbox-0.4.5 lib/lockbox/padding.rb
lockbox-0.4.4 lib/lockbox/padding.rb
lockbox-0.4.3 lib/lockbox/padding.rb
lockbox-0.4.2 lib/lockbox/padding.rb
lockbox-0.4.1 lib/lockbox/padding.rb
lockbox-0.4.0 lib/lockbox/padding.rb
lockbox-0.3.7 lib/lockbox/padding.rb
lockbox-0.3.6 lib/lockbox/padding.rb
lockbox-0.3.5 lib/lockbox/padding.rb
lockbox-0.3.4 lib/lockbox/padding.rb