I'm trying to set an encrypted file field's value programmatically. I'm using Encrypted Files module. I have successfully configured a file field, and it works for the contents created using the node add form.

In a custom code, I'm getting a file using the HttpClient and want to attach to a media. I could get the file, encyrpt and save it. However, if I want to open the file, it is broken.

What I'm doing is like the following:

  $client = Drupal::httpClient();

  // Get data from remote page and encrypt using the encryption profile
  $data = (string) $client->get('https://example.com/download.php?file=123')
  $encryptionProfile = Drupal::entityTypeManager()
  $encryptedData = Drupal::service('encryption')
    ->encrypt($data, $encryptionProfile);

  // Create media entity and prepare destination directory
  $media = Drupal::entityTypeManager()->getStorage('media')
    ->create(['bundle' => 'my_media_type']);
  $destination = 'encrypt://my_encryption_profile/path/to/files'
    ->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY);

  // Save data as file and attach to the media
  $filename = 'download.pdf';
  $file = file_save_data($encryptedData, $destination . '/' . $filename);
  $media->set('encrypted_file', ['target_id' => $file->id()]);
  • 1
    The encrypt stream wrapper is a scheme wrapper which encrypts / decrypts automatically - so you're possibly doubling up by encrypting the data yourself
    – Clive
    Jan 10, 2022 at 23:38
  • I was also expecting the same, but if I use $data instead of $encryptedData like file_save_data($data, $destination . '/' . $filename), the file is saved without encryption and I can open it on the file system. Downloading the file over the stream wrapper still doesn't work. Jan 11, 2022 at 2:06
  • 1
    @Clive thanks for showing me the right direction. I was first downloading the file with the httpClient and then saving it using file_save_data. This was somehow skipping the scheme wrapper for whatever reason. That's why I was trying to encrypt it manually before saving. I changed the code and used httpClient directly to download into the destination, and it worked without manually encrypting! I'll post the detailed solution in the next days as soon as I get some time. Jan 11, 2022 at 11:11


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.