Class: Can::Crypto

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

Constant Summary collapse

CIPHER =
"AES-256-CBC"

Class Method Summary collapse

Class Method Details

.decrypt(content, password) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/can/crypto.rb', line 26

def self.decrypt(content, password)
  digest = Digest::SHA1.hexdigest(password)
  init, encrypted = content.split("--").map do |v|
    Base64.strict_decode64(v)
  end

  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.decrypt
  cipher.key = digest[0..31]
  cipher.iv = init

  cipher.update(encrypted) + cipher.final
end

.encrypt(content, password) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/can/crypto.rb', line 10

def self.encrypt(content, password)
  digest = Digest::SHA1.hexdigest(password)
  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.encrypt
  cipher.key = digest[0..31]
  cipher.iv  = iv = cipher.random_iv
  encrypted  = cipher.update(content) + cipher.final

  binit = Base64.strict_encode64(iv)
  ilen  = binit.length.to_s
  blen  = Base64.strict_encode64(ilen)
  bdata = Base64.strict_encode64(encrypted)
  # blen + "--" + binit + "--" + bdata
  binit + "--" + bdata
end