/**
* Encrypt an assertion.
*
* This function takes in a SAML2_Assertion and encrypts it if encryption of
* assertions are enabled in the metadata.
*
* @param SimpleSAML_Configuration $srcMetadata The metadata of the sender (IdP).
* @param SimpleSAML_Configuration $dstMetadata The metadata of the recipient (SP).
* @param SAML2_Assertion $assertion The assertion we are encrypting.
* @return SAML2_Assertion|SAML2_EncryptedAssertion The assertion.
*/
public static function encryptAssertion(SimpleSAML_Configuration $srcMetadata, SimpleSAML_Configuration $dstMetadata, SAML2_Assertion $assertion)
{
$encryptAssertion = $dstMetadata->getBoolean('assertion.encryption', NULL);
if ($encryptAssertion === NULL) {
$encryptAssertion = $srcMetadata->getBoolean('assertion.encryption', FALSE);
}
if (!$encryptAssertion) {
/* We are _not_ encrypting this assertion, and are therefore done. */
return $assertion;
}
$sharedKey = $dstMetadata->getString('sharedkey', NULL);
if ($sharedKey !== NULL) {
$key = new XMLSecurityKey(XMLSecurityKey::AES128_CBC);
$key->loadKey($sharedKey);
} else {
/* Find the certificate that we should use to encrypt messages to this SP. */
$certArray = SimpleSAML_Utilities::loadPublicKey($dstMetadata->toArray(), TRUE);
if (!array_key_exists('PEM', $certArray)) {
throw new Exception('Unable to locate key we should use to encrypt the assertionst ' . 'to the SP: ' . var_export($dstMetadata->getString('entityid'), TRUE) . '.');
}
$pemCert = $certArray['PEM'];
/* Extract the public key from the certificate for encryption. */
$key = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type' => 'public'));
$key->loadKey($pemCert);
}
$ea = new SAML2_EncryptedAssertion();
$ea->setAssertion($assertion, $key);
return $ea;
}