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.

Parameters:

  • encrypted_env (String)

    json string with aes_key and encrypted_magic_envelope

  • privkey (OpenSSL::PKey::RSA)

    private key for decryption

Returns:

  • (Nokogiri::XML::Element)

    decrypted magic envelope xml



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

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.transform_values {|v| Base64.decode64(v) }

  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.

Parameters:

  • magic_env (Nokogiri::XML::Element)

    XML root node of a magic envelope

  • pubkey (OpenSSL::PKey::RSA)

    recipient public_key

Returns:

  • (String)

    json string



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

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.transform_values {|v| Base64.strict_encode64(v) }
  encrypted_key = Base64.strict_encode64(pubkey.public_encrypt(JSON.generate(encoded_key)))

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