Module: WeWhisper::Cipher

Included in:
Cryptor, Whisper
Defined in:
lib/we_whisper/cipher.rb

Constant Summary collapse

BLOCK_SIZE =
32
CIPHER =
'AES-256-CBC'.freeze

Instance Method Summary collapse

Instance Method Details

#cipher_decrypt(msg, encoding_aes_key) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/we_whisper/cipher.rb', line 25

def cipher_decrypt(msg, encoding_aes_key)
  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.decrypt

  cipher.padding = 0
  key_data = Base64.decode64(encoding_aes_key + '=')
  cipher.key = key_data
  cipher.iv = key_data[0..16]

  plain = cipher.update(msg) + cipher.final
  decode_padding(plain)
end

#cipher_encrypt(plain, encoding_aes_key) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/we_whisper/cipher.rb', line 13

def cipher_encrypt(plain, encoding_aes_key)
  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.encrypt

  cipher.padding = 0
  key_data = Base64.decode64(encoding_aes_key + '=')
  cipher.key = key_data
  cipher.iv = key_data[0..16]

  cipher.update(plain) + cipher.final
end

#pack(content, app_id) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/we_whisper/cipher.rb', line 38

def pack(content, app_id)
  random = SecureRandom.hex(8)
  text = content.force_encoding('ASCII-8BIT')
  msg_len = [text.length].pack('N')

  encode_padding("#{random}#{msg_len}#{text}#{app_id}")
end

#unpack(msg) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/we_whisper/cipher.rb', line 46

def unpack(msg)
  msg = decode_padding(msg)
  msg_len = msg[16, 4].reverse.unpack('V')[0]
  content = msg[20, msg_len]
  app_id = msg[(20 + msg_len)..-1]

  [content, app_id]
end