Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 63 lines (54 sloc) 1.794 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
# Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.

module Encryptor
  module Public
    def encrypt cleartext
      aes_key = gen_aes_key
      ciphertext = aes_encrypt(cleartext, aes_key)
      encrypted_key = encrypt_aes_key aes_key
      cipher_hash = {:aes_key => encrypted_key, :ciphertext => ciphertext}
      Base64.encode64s( cipher_hash.to_json )
    end

    def gen_aes_key
      cipher = OpenSSL::Cipher.new('AES-256-CBC')
      key = cipher.random_key
      iv = cipher.random_iv
      {'key' => Base64.encode64s(key), 'iv' => Base64.encode64s(iv)}
    end

    def aes_encrypt(txt, key)
      cipher = OpenSSL::Cipher.new('AES-256-CBC')
      cipher.encrypt
      cipher.key = Base64.decode64 key['key']
      cipher.iv = Base64.decode64 key['iv']
      ciphertext = ''
      ciphertext << cipher.update(txt)
      ciphertext << cipher.final
      Base64.encode64s(ciphertext)
    end

    def encrypt_aes_key key
      Base64.encode64s(public_key.public_encrypt( key.to_json ))
    end
  end

  module Private
    def decrypt cipher_json
      json = JSON.parse(Base64.decode64 cipher_json)
      aes_key = get_aes_key json['aes_key']
      aes_decrypt(json['ciphertext'], aes_key)
    end

    def get_aes_key encrypted_key
      clear_key = encryption_key.private_decrypt( Base64.decode64 encrypted_key )
      JSON::parse(clear_key)
    end

    def aes_decrypt(ciphertext, key)
      cipher = OpenSSL::Cipher.new('AES-256-CBC')
      cipher.decrypt
      cipher.key = Base64.decode64 key['key']
      cipher.iv = Base64.decode64 key['iv']
      txt = ''
      txt << cipher.update(Base64.decode64 ciphertext)
      txt << cipher.final
      txt
    end

  end
end
Something went wrong with that request. Please try again.