Class: Ktct::DigitalEnvelop

Inherits:
Object
  • Object
show all
Defined in:
lib/ktct/digital_envelop.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content) ⇒ DigitalEnvelop

Returns a new instance of DigitalEnvelop.



8
9
10
# File 'lib/ktct/digital_envelop.rb', line 8

def initialize(content)
  _, @key = content.split('|')
end

Instance Attribute Details

#aesObject

Returns the value of attribute aes.



7
8
9
# File 'lib/ktct/digital_envelop.rb', line 7

def aes
  @aes
end

#algorithmObject

Returns the value of attribute algorithm.



7
8
9
# File 'lib/ktct/digital_envelop.rb', line 7

def algorithm
  @algorithm
end

#keyObject

Returns the value of attribute key.



7
8
9
# File 'lib/ktct/digital_envelop.rb', line 7

def key
  @key
end

Class Method Details

.getObject



43
44
45
# File 'lib/ktct/digital_envelop.rb', line 43

def get
  new('01|%s' % SecureRandom.uuid.gsub(/-/, '')[0, 16])
end

Instance Method Details

#add_padding(content) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/ktct/digital_envelop.rb', line 30

def add_padding(content)
  if content.bytesize % 16 == 0
    content
  else
    content + "\x00" * (16 - content.bytesize % 16)
  end
end

#decrypt(content) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/ktct/digital_envelop.rb', line 21

def decrypt(content)
  @aes = OpenSSL::Cipher::AES.new(128, :CBC)
  @aes.decrypt
  @aes.padding = 0
  @aes.key = @key
  @aes.iv = @key
  Base64.decode64((@aes.update([content].pack('H*')) + @aes.final).strip).force_encoding('UTF-8')
end

#encrypt(content) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/ktct/digital_envelop.rb', line 12

def encrypt(content)
  @aes = OpenSSL::Cipher::AES.new(128, :CBC)
  @aes.encrypt
  @aes.padding = 0
  @aes.key = @key
  @aes.iv = @key
  (@aes.update(add_padding(Base64.encode64(content))) + @aes.final).unpack('H*').first
end

#to_sObject



38
39
40
# File 'lib/ktct/digital_envelop.rb', line 38

def to_s
  "01|#{@key}"
end