/** * Encryptes the given node and adds it to the list of references. * * @param DOMNode $node DOM node to encrypt * @param string $type \ass\XmlSecurity\Enc::ELEMENT || \ass\XmlSecurity\Enc::CONTENT * @param Key $key Security key to use for encryption * @param DOMElement $referenceList Reference list element * @param DOMElement $keyInfo KeyInfo element * * @return DOMNode */ public static function encryptNode(DOMNode $node, $type, Key $key, DOMElement $referenceList = null, $keyInfo = null) { if ($type != self::ELEMENT && $type != self::CONTENT) { throw InvalidArgumentException('type', 'Value must be either \\ass\\XmlSecurity\\Enc::CONTENT or \\ass\\XmlSecurity\\Enc::ELEMENT'); } if ($node instanceof DOMDocument) { $doc = $node; } else { $doc = $node->ownerDocument; } $encryptedData = $doc->createElementNS(self::NS_XMLENC, self::PFX_XMLENC . ':EncryptedData'); if (null !== $referenceList) { $uri = 'Id-' . DSig::generateUUID(); $encryptedData->setAttribute("Id", $uri); } $cipherData = $doc->createElementNS(self::NS_XMLENC, self::PFX_XMLENC . ':CipherData'); $encryptedData->appendChild($cipherData); $cipherValue = $doc->createElementNS(self::NS_XMLENC, self::PFX_XMLENC . ':CipherValue'); $cipherData->appendChild($cipherValue); $dataToEncrypt = ''; switch ($type) { case self::ELEMENT: $dataToEncrypt = $node->C14N(false, false); $encryptedData->setAttribute('Type', self::ELEMENT); break; case self::CONTENT: foreach ($node->childNodes as $child) { $dataToEncrypt .= $child->C14N(false, false); } $encryptedData->setAttribute('Type', self::CONTENT); break; } $encryptionMethod = $doc->createElementNS(self::NS_XMLENC, self::PFX_XMLENC . ':EncryptionMethod'); $encryptionMethod->setAttribute('Algorithm', $key->getAlgorithm()); $encryptedData->insertBefore($encryptionMethod, $cipherData); if (!is_null($keyInfo)) { $encryptedData->insertBefore($keyInfo, $cipherData); } $encryptedDataString = base64_encode($key->encryptData($dataToEncrypt)); $value = $doc->createTextNode($encryptedDataString); $cipherValue->appendChild($value); // replace nodes switch ($type) { case self::ELEMENT: if ($node instanceof DOMDocument) { $node->replaceChild($encryptedData, $node->documentElement); } else { $node->parentNode->replaceChild($encryptedData, $node); } break; case self::CONTENT: while ($node->firstChild) { $node->removeChild($node->firstChild); } $node->appendChild($encryptedData); break; } if (null !== $referenceList) { $dataReference = $doc->createElementNS(self::NS_XMLENC, self::PFX_XMLENC . ':DataReference'); $dataReference->setAttribute('URI', '#' . $uri); $referenceList->appendChild($dataReference); } return $encryptedData; }