Module: DiasporaFederation::Salmon::EncryptedMagicEnvelope

Defined in:
lib/diaspora_federation/salmon/encrypted_magic_envelope.rb

Overview

This is a simple crypt-wrapper for MagicEnvelope.

The wrapper is JSON with the following structure:

{
  "aes_key": "...",
  "encrypted_magic_envelope": "..."
}

aes_key is encrypted using the recipients public key, and contains the AES key and iv as JSON:

{
  "key": "...",
  "iv": "..."
}

encrypted_magic_envelope is encrypted using the key and iv from aes_key. Once decrypted it contains the MagicEnvelope xml:

<me:env>
  ...
</me:env>

All JSON-values (aes_key, encrypted_magic_envelope, key and iv) are base64 encoded.

Class Method Summary collapse

Class Method Details

.decrypt(encrypted_env, privkey) ⇒ Nokogiri::XML::Element

Decrypts the AES key with the private key of the receiver and decrypts the encrypted MagicEnvelope with it.


50
51
52
53
54
55
56
57
58
# File 'lib/diaspora_federation/salmon/encrypted_magic_envelope.rb', line 50

def self.decrypt(encrypted_env, privkey)
  encrypted_json = JSON.parse(encrypted_env)

  encoded_key = JSON.parse(privkey.private_decrypt(Base64.decode64(encrypted_json["aes_key"])))
  key = encoded_key.map {|k, v| [k, Base64.decode64(v)] }.to_h

  xml = AES.decrypt(encrypted_json["encrypted_magic_envelope"], key["key"], key["iv"])
  Nokogiri::XML(xml).root
end

.encrypt(magic_env, pubkey) ⇒ String

Generates a new random AES key and encrypts the MagicEnvelope with it. Then encrypts the AES key with the receivers public key.


35
36
37
38
39
40
41
42
43
# File 'lib/diaspora_federation/salmon/encrypted_magic_envelope.rb', line 35

def self.encrypt(magic_env, pubkey)
  key = AES.generate_key_and_iv
  encrypted_env = AES.encrypt(magic_env.to_xml, key[:key], key[:iv])

  encoded_key = key.map {|k, v| [k, Base64.strict_encode64(v)] }.to_h
  encrypted_key = Base64.strict_encode64(pubkey.public_encrypt(JSON.generate(encoded_key)))

  JSON.generate(aes_key: encrypted_key, encrypted_magic_envelope: encrypted_env)
end