55namespace SimpleSAML \SAML2 \XML ;
66
77use SimpleSAML \SAML2 \Compat \ContainerSingleton ;
8+ use SimpleSAML \XMLSchema \Type \AnyURIValue ;
9+ use SimpleSAML \XMLSchema \Type \Base64BinaryValue ;
10+ use SimpleSAML \XMLSecurity \Alg \Encryption \EncryptionAlgorithmFactory ;
11+ use SimpleSAML \XMLSecurity \Alg \Encryption \EncryptionAlgorithmInterface ;
12+ use SimpleSAML \XMLSecurity \Constants as C ;
13+ use SimpleSAML \XMLSecurity \Key \SymmetricKey ;
14+ use SimpleSAML \XMLSecurity \XML \ds \KeyInfo ;
815use SimpleSAML \XMLSecurity \XML \EncryptableElementTrait as ParentEncryptableElementTrait ;
16+ use SimpleSAML \XMLSecurity \XML \xenc \CipherData ;
17+ use SimpleSAML \XMLSecurity \XML \xenc \CipherValue ;
18+ use SimpleSAML \XMLSecurity \XML \xenc \EncryptedData ;
19+ use SimpleSAML \XMLSecurity \XML \xenc \EncryptedKey ;
20+ use SimpleSAML \XMLSecurity \XML \xenc \EncryptionMethod ;
21+
22+ use function in_array ;
923
1024/**
1125 * Trait aggregating functionality for elements that are encrypted.
@@ -17,6 +31,63 @@ trait EncryptableElementTrait
1731 use ParentEncryptableElementTrait;
1832
1933
34+ /**
35+ * Encryt this object.
36+ *
37+ * @param \SimpleSAML\XMLSecurity\Alg\Encryption\EncryptionAlgorithmInterface $encryptor The encryptor to use,
38+ * either to encrypt the object itself, or to encrypt a session key (if the encryptor implements a key transport
39+ * algorithm).
40+ *
41+ * @return \SimpleSAML\XMLSecurity\XML\xenc\EncryptedData
42+ */
43+ public function encrypt (EncryptionAlgorithmInterface $ encryptor ): EncryptedData
44+ {
45+ $ keyInfo = null ;
46+ if (in_array ($ encryptor ->getAlgorithmId (), C::$ KEY_TRANSPORT_ALGORITHMS )) {
47+ // the encryptor uses a key transport algorithm, use that to generate a session key
48+ $ sessionKey = SymmetricKey::generate ($ this ->sessionKeyLen );
49+
50+ $ encryptedKey = EncryptedKey::fromKey (
51+ $ sessionKey ,
52+ $ encryptor ,
53+ new EncryptionMethod (
54+ AnyURIValue::fromString ($ encryptor ->getAlgorithmId ()),
55+ ),
56+ );
57+
58+ $ keyInfo = new KeyInfo ([$ encryptedKey ]);
59+
60+ $ factory = new EncryptionAlgorithmFactory (
61+ $ this ->getBlacklistedAlgorithms () ?? EncryptionAlgorithmFactory::DEFAULT_BLACKLIST ,
62+ );
63+ $ encryptor = $ factory ->getAlgorithm ($ this ->blockCipherAlgId , $ sessionKey );
64+ $ encryptor ->setBackend ($ this ->getEncryptionBackend ());
65+ }
66+
67+ $ xmlRepresentation = $ this ->toXML ();
68+
69+ return new EncryptedData (
70+ new CipherData (
71+ new CipherValue (
72+ Base64BinaryValue::fromString (
73+ base64_encode ($ encryptor ->encrypt (
74+ $ xmlRepresentation ->ownerDocument ->saveXML ($ xmlRepresentation ),
75+ )),
76+ ),
77+ ),
78+ ),
79+ null ,
80+ AnyURIValue::fromString (C::XMLENC_ELEMENT ),
81+ null ,
82+ null ,
83+ new EncryptionMethod (
84+ AnyURIValue::fromString ($ encryptor ->getAlgorithmId ()),
85+ ),
86+ $ keyInfo ,
87+ );
88+ }
89+
90+
2091 /**
2192 * @return array|null
2293 */
0 commit comments