Sha256: 1c72ffe717dc0a7f1fd845c6421bbb505e70a77ba5524a1ca7228c422a5b8629

Contents?: true

Size: 1.1 KB

Versions: 12

Compression:

Stored size: 1.1 KB

Contents

module RASN1
  module Types

    # ASN.1 Integer
    # @author Sylvain Daubert
    class Integer < Primitive
      TAG = 0x02

      # @return [Integer]
      def to_i
        @value || @default || 0
      end

      private

      def value_to_der(value=nil)
        v = value || @value
        size = v.bit_length / 8 + (v.bit_length % 8 > 0 ? 1 : 0)
        size = 1 if size == 0
        comp_value = if v > 0
                       # If MSB is 1, increment size to set initial octet
                       # to 0 to amrk it as a positive integer
                       size += 1 if v >> (size * 8 - 1) == 1
                       v
                     else
                       ~(v.abs) + 1
                     end
        ary = []
        size.times { ary << (comp_value & 0xff); comp_value >>= 8 }
        ary.reverse.pack('C*')
      end

      def der_to_value(der, ber: false)
        ary = der.unpack('C*')
        @value = ary.reduce(0) { |len, b| (len << 8) | b }
        if ary[0] & 0x80 == 0x80
          @value = -((~@value & ((1 << @value.bit_length) - 1)) + 1)
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
rasn1-0.6.5 lib/rasn1/types/integer.rb
rasn1-0.6.4 lib/rasn1/types/integer.rb
rasn1-0.6.3 lib/rasn1/types/integer.rb
rasn1-0.6.2 lib/rasn1/types/integer.rb
rasn1-0.6.1 lib/rasn1/types/integer.rb
rasn1-0.6.0 lib/rasn1/types/integer.rb
rasn1-0.5.0 lib/rasn1/types/integer.rb
rasn1-0.4.0 lib/rasn1/types/integer.rb
rasn1-0.3.1 lib/rasn1/types/integer.rb
rasn1-0.3.0 lib/rasn1/types/integer.rb
rasn1-0.2.0 lib/rasn1/types/integer.rb
rasn1-0.1.0 lib/rasn1/types/integer.rb