class Nis::Struct::Message

@attr [String] value @attr [Integer] type @attr [String] payload @attr [String] public_key

Constants

TYPE_ENCRYPTED
TYPE_PLAIN

Attributes

private_key[RW]
public_key[RW]
type[R]
value[R]

Public Class Methods

build(attrs) click to toggle source
# File lib/nis/struct/message.rb, line 13
def self.build(attrs)
  if attrs[:type] == TYPE_ENCRYPTED
    new(attrs[:payload], type: :encrypted)
  end
end
new(value = '', type: :plain, private_key: nil, public_key: nil) click to toggle source
# File lib/nis/struct/message.rb, line 19
def initialize(value = '', type: :plain, private_key: nil, public_key: nil)
  @value = value
  @type = (type == :encrypted) ? TYPE_ENCRYPTED : TYPE_PLAIN
  @private_key = private_key
  @public_key = public_key
end

Public Instance Methods

==(other) click to toggle source

@return [Boolean]

# File lib/nis/struct/message.rb, line 71
def ==(other)
  @value == other.value
end
bytesize() click to toggle source

@return [Integer]

# File lib/nis/struct/message.rb, line 51
def bytesize
  payload.bytesize
end
decrypt!() click to toggle source
# File lib/nis/struct/message.rb, line 33
def decrypt!
  bin_sk = fix_private_key(@private_key).scan(/../).map(&:hex).reverse.pack('C*')
  bin_pk = (public_key || @public_key).scan(/../).map(&:hex).pack('C*')
  @value = Nis::Util::Ed25519.decrypt(bin_sk, bin_pk, payload)
  @type = TYPE_PLAIN
end
encrypt!() click to toggle source
# File lib/nis/struct/message.rb, line 26
def encrypt!
  bin_sk = fix_private_key(@private_key).scan(/../).map(&:hex).reverse.pack('C*')
  bin_pk = (public_key || @public_key).scan(/../).map(&:hex).pack('C*')
  @value = Nis::Util::Ed25519.encrypt(bin_sk, bin_pk, value)
  @type = TYPE_ENCRYPTED
end
encrypted?() click to toggle source

@return [Boolean]

# File lib/nis/struct/message.rb, line 41
def encrypted?
  @type == TYPE_ENCRYPTED
end
payload() click to toggle source
# File lib/nis/struct/message.rb, line 75
def payload
  (value =~ /\Afe/ || encrypted?) ? value : value.unpack('H*').first
end
plain?() click to toggle source

@return [Boolean]

# File lib/nis/struct/message.rb, line 46
def plain?
  @type == TYPE_PLAIN
end
to_hash() click to toggle source

@return [Hash]

# File lib/nis/struct/message.rb, line 61
def to_hash
  { payload: payload, type: @type }
end
to_s() click to toggle source

@return [String]

# File lib/nis/struct/message.rb, line 66
def to_s
  @value.to_s
end
valid?() click to toggle source

@return [Boolean]

# File lib/nis/struct/message.rb, line 56
def valid?
  bytesize <= 1024
end

Private Instance Methods

fix_private_key(key) click to toggle source
# File lib/nis/struct/message.rb, line 81
def fix_private_key(key)
  "#{'0' * 64}#{key.sub(/^00/i, '')}"[-64, 64]
end