Class: SharedSecret

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ SharedSecret

Returns a new instance of SharedSecret.



14
15
16
17
18
19
20
# File 'lib/shared_secret.rb', line 14

def initialize(io)
  if ARGV.size == 0
    STDERR.puts "Please enter the message to be processed followd by ^D:"
  end
  @input = io.read
  @mode = encrypted_input? ? :decrypt : :encrypt
end

Instance Attribute Details

#modeObject (readonly)

Returns the value of attribute mode.



3
4
5
# File 'lib/shared_secret.rb', line 3

def mode
  @mode
end

Class Method Details

.runObject



5
6
7
8
9
10
11
12
# File 'lib/shared_secret.rb', line 5

def self.run
  app = SharedSecret.new(ARGF)
  output = app.process
  label = "--- OUTPUT (#{app.mode}) ---"
  STDERR.puts label
  puts output
  STDERR.puts "-" * label.size
end

Instance Method Details

#decrypt(cypher) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/shared_secret.rb', line 31

def decrypt(cypher)
  message = JSON.parse(@input.unpack('m')[0])['shared-secret']
  cipher = OpenSSL::Cipher::Cipher.new(message['cipher'])
  digest = OpenSSL::Digest::Digest.new(message['digest'])
  digest << prompt('secret key?')
  cipher.key = expand_key(digest.digest)
  if message['iv']
    cipher.iv = message['iv'].unpack('m')[0]
  else
    cipher.iv = expand_key(digest.digest)
  end
  cipher.decrypt
  cipher.update(message['message'].unpack('m')[0]) + cipher.final
end

#encrypt(text) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/shared_secret.rb', line 46

def encrypt(text)
  cipher_algorithm = select_cipher
  cipher = OpenSSL::Cipher::Cipher.new(cipher_algorithm)
  # TODO: support more digest types including SHA256 and
  # cipher texts.
  digest = OpenSSL::Digest::Digest.new('sha1')
  digest << prompt('secret key?')
  cipher.key = expand_key(digest.digest)
  cipher.iv = expand_key(digest.digest)
  cipher.encrypt
  message = cipher.update(text) + cipher.final
  [{'shared-secret' => {
    'cipher' => cipher_algorithm,
    'digest' => 'sha1',
    'message' => [message].pack('m')
  }}.to_json].pack('m')
end

#processObject



22
23
24
25
26
27
28
29
# File 'lib/shared_secret.rb', line 22

def process
  case @mode
  when :decrypt
    decrypt(@input)
  when :encrypt
    encrypt(@input)
  end
end

#select_cipherObject



64
65
66
67
68
69
70
71
72
73
# File 'lib/shared_secret.rb', line 64

def select_cipher
  loop do
    algo = prompt('cipher algorithm (l to list)?', :string, 'bf')
    if algo == 'l'
      puts OpenSSL::Cipher.ciphers
      next
    end
    break algo
  end
end