@@ -166,17 +166,11 @@ public function decrypt(string $encryptedData, bool $legacy = false): string
166166 throw new IvGenerateException ();
167167 }
168168
169- $ this ->iv = substr ($ c , 0 , $ iv_len );
170-
171- if ($ legacy ) {
172- // IV-TAG-EncryptedData
173- $ this ->tag = substr ($ c , $ iv_len , static ::DEFAULT_GCM_TAG_LENGTH ); // tag is 16 bytes after iv
174- $ encryptedBytes = substr ($ c , $ iv_len + static ::DEFAULT_GCM_TAG_LENGTH ); // encrypted data are at the end
175- } else {
176- // IV-EncryptedData-TAG
177- $ encryptedBytes = substr ($ c , $ iv_len , -static ::DEFAULT_GCM_TAG_LENGTH ); // encrypted data are in the middle
178- $ this ->tag = substr ($ c , -static ::DEFAULT_GCM_TAG_LENGTH ); // tag is at the end
179- }
169+ [$ this ->iv , $ encryptedBytes , $ this ->tag ] = $ this ->parsePayload (
170+ cipherText: $ c ,
171+ ivLength: $ iv_len ,
172+ legacy: $ legacy
173+ );
180174
181175 $ decryptedText = openssl_decrypt (
182176 $ encryptedBytes ,
@@ -194,6 +188,26 @@ public function decrypt(string $encryptedData, bool $legacy = false): string
194188 return $ decryptedText ;
195189 }
196190
191+ /**
192+ * Parse payload from encrypted data
193+ *
194+ * @param string $cipherText
195+ * @param int $ivLength
196+ * @param bool $legacy
197+ * If true, expects IV-TAG-EncryptedData format
198+ * If false, expects IV-EncryptedData-TAG format
199+ * @return array That contains IV, EncryptedData and TAG in that order
200+ */
201+ protected function parsePayload (string $ cipherText , int $ ivLength , bool $ legacy = false ): array
202+ {
203+ $ iv = substr ($ cipherText , 0 , $ ivLength );
204+ $ tagLength = static ::DEFAULT_GCM_TAG_LENGTH ;
205+
206+ return $ legacy
207+ ? [$ iv , substr ($ cipherText , $ ivLength + $ tagLength ), substr ($ cipherText , $ ivLength , $ tagLength )]
208+ : [$ iv , substr ($ cipherText , $ ivLength , -$ tagLength ), substr ($ cipherText , -$ tagLength )];
209+ }
210+
197211 /**
198212 * Seal data using AES-256-CBC and public key
199213 *
0 commit comments