Method: Saml::Util.encrypt_assertion

Defined in:
lib/saml/util.rb

.encrypt_assertion(assertion, key_descriptor_or_certificate, include_certificate: false) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/saml/util.rb', line 63

def encrypt_assertion(assertion, key_descriptor_or_certificate, include_certificate: false)
  case key_descriptor_or_certificate
  when OpenSSL::X509::Certificate
    certificate = key_descriptor_or_certificate
    key_name    = nil
  when Saml::Elements::KeyDescriptor
    certificate = key_descriptor_or_certificate.certificate
    key_name    = key_descriptor_or_certificate.key_info.key_name
  else
    fail ArgumentError, "Expecting Certificate or KeyDescriptor got: #{key_descriptor_or_certificate.class}"
  end

  assertion = assertion.to_xml(nil, nil, false) if assertion.is_a?(Assertion) # create xml without instruct

  encrypted_data = Xmlenc::Builder::EncryptedData.new
  encrypted_data.set_encryption_method(algorithm: 'http://www.w3.org/2001/04/xmlenc#aes128-cbc')

  encrypted_key = encrypted_data.encrypt(assertion.to_s)
  encrypted_key.set_encryption_method(algorithm:               'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p',
                                      digest_method_algorithm: 'http://www.w3.org/2000/09/xmldsig#sha1')
  encrypted_key.key_info = if include_certificate || key_name
    key_info = Saml::Elements::KeyInfo.new(include_certificate ? certificate.to_pem : nil)
    key_info.key_name = key_name
    key_info
  end
  encrypted_key.encrypt(certificate.public_key)

  Saml::Elements::EncryptedAssertion.new(encrypted_data: encrypted_data, encrypted_keys: encrypted_key)
end