Owncloud 8 : manually decrypt files
Par Mathieu le lundi 20 avril 2015, 19:01 - Hacks - Lien permanent
Owncloud has the ability to encrypt files. You can restore your files with a complete backup/restore of your Owncloud folder, but what if you want to restore just one file from a previous backup ? Here is the code for a one-shot file decryption.
This code is the solution I posted on Github : https://github.com/owncloud/core/issues/13591
2015-08-05 : UPDATE : to make it work with binary files, use the following code instead :
<?php // Replace these with your custom values $datadir = '_PATH_TO_DATADIR_INCLUDING_TRAILING_SLASH_'; $filepath = 'some/directory/relative/to/datadir/myfile.txt'; $username = '_OWNCLOUD_LOGIN_'; $password = '_OWNCLOUD_PASSWORD_'; require_once '_PATH_TO_OWNCLOUD_/apps/files_encryption/lib/crypt.php'; // first get users private key and decrypt it $encryptedUserKey = file_get_contents($datadir . $username . '/files_encryption/' . $username . '.privateKey'); $decryptedUserKey = OCA\Files_Encryption\Crypt::decryptPrivateKey($encryptedUserKey, $password); // now we need to decrypt the file-key, therefore we use our private key and the share key $shareKey = file_get_contents($datadir . $username . '/files_encryption/keys/' . $filepath . '/' . $username . '.shareKey'); $encryptedKeyfile = file_get_contents($datadir . $username . '/files_encryption/keys/' . $filepath . '/fileKey'); $decryptedKeyfile = OCA\Files_Encryption\Crypt::multiKeyDecrypt($encryptedKeyfile, $shareKey, $decryptedUserKey); // finally we can use the decrypted file-key to decrypt the file // but first, strip header block $handle = fopen($datadir . $username . '/files/' . $filepath, 'r'); // if this block contained the header we move on to the next block if (OCA\Files_Encryption\Crypt::isHeader($data)) { $header = OCA\Files_Encryption\Crypt::parseHeader($data); $cipher = OCA\Files_Encryption\Crypt::getCipher($header); } else { die('Cannot find header'); } // Decrypt the content block by block $decryptedContent = ''; while ($data = fread($handle, OCA\Files_Encryption\Crypt::BLOCKSIZE)) { $decryptedContent .= OCA\Files_Encryption\Crypt::symmetricDecryptFileContent($data, $decryptedKeyfile, $cipher); } fclose($handle); // Save the decrypted file file_put_contents(str_replace('/', '-', $filepath), $decryptedContent);