/** * Tests the encrypt & decrypt method. * * @covers ::__construct * @covers ::encrypt * @covers ::decrypt * @covers ::validate * * @dataProvider encryptionDataProvider */ public function testEncryptDecrypt($key, $valid_key) { // Set up expectations for Key. $this->key->expects($this->any())->method('getKeyValue')->will($this->returnValue($key)); if ($valid_key) { // Set up expectations for encryption method. $this->encryptionMethod->expects($this->once())->method('encrypt')->will($this->returnValue("encrypted_text")); $this->encryptionMethod->expects($this->once())->method('decrypt')->will($this->returnValue("decrypted_text")); // Set up expectations for encryption profile. $this->encryptionProfile->expects($this->any())->method('getEncryptionKey')->will($this->returnValue($this->key)); $this->encryptionProfile->expects($this->any())->method('getEncryptionMethod')->will($this->returnValue($this->encryptionMethod)); $this->encryptionProfile->expects($this->any())->method('validate')->will($this->returnValue(array())); } else { // Set up expectations for encryption profile. $this->encryptionProfile->expects($this->never())->method('getEncryptionKey'); $this->encryptionProfile->expects($this->never())->method('getEncryptionMethod'); $this->encryptionProfile->expects($this->any())->method('validate')->will($this->returnValue(array("Validation error"))); $this->setExpectedException('\\Drupal\\encrypt\\Exception\\EncryptException'); } $service = new EncryptService($this->encryptManager, $this->keyRepository); $encrypted_text = $service->encrypt("text_to_encrypt", $this->encryptionProfile); $decrypted_text = $service->decrypt("text_to_decrypt", $this->encryptionProfile); if ($valid_key) { $this->assertEquals("encrypted_text", $encrypted_text); $this->assertEquals("decrypted_text", $decrypted_text); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $trigger = $form_state->getTriggeringElement(); switch ($trigger['#name']) { case 'encrypt': if ($to_encrypt = $form_state->getValue('to_encrypt')) { $encrypted_text = $this->encryptService->encrypt($to_encrypt, $this->entity); if ($form_state->getValue('encrypt_base64')) { $encrypted_text = base64_encode($encrypted_text); } $form_state->setValue('encrypted', $encrypted_text); } break; case 'decrypt': if ($to_decrypt = $form_state->getValue('to_decrypt')) { if ($form_state->getValue('decrypt_base64')) { $to_decrypt = base64_decode($to_decrypt); } $decrypted_text = $this->encryptService->decrypt($to_decrypt, $this->entity); $form_state->setValue('decrypted', $decrypted_text); } break; } $form_state->setRebuild(); }