+ File Decryption

This commit is contained in:
2021-02-28 14:10:12 +02:00
parent 2645ce64fa
commit cb38762215
3 changed files with 71 additions and 16 deletions

58
lib.php
View File

@@ -15,14 +15,23 @@ class kpcrypt {
private $key = null;
/**
* Define the number of blocks that should be read from the source file for each chunk.
* For 'AES-128-CBC' each block consist of 16 bytes.
* So if we read 10,000 blocks we load 160kb into memory. You may adjust this value
* to read/write shorter or longer chunks.
*
* Define the number of blocks that should be read from the source file for each chunk.
* For 'AES-128-CBC' each block consist of 16 bytes.
* So if we read 10,000 blocks we load 160kb into memory. You may adjust this value
* to read/write shorter or longer chunks.
*
* The higher this size is, the faster the file will be
* processed but the more memory will in turn be also used
*
*/
private $blocks = 10000;
// A log of all of the errors, rather nice for debugging
/**
* A log of all of the errors, rather nice for debugging
* Please don't write to this, only read from it since
* it should only store errors about this class.
*/
private $errorLog = [];
// The encryption cipher to use
@@ -148,6 +157,11 @@ class kpcrypt {
// #endregion
/**
* File encryption should only be used on larger files ( 512kb+ )
* Since the string encryption will work better on the smaller files, since it's all
* in the memory, this simlpy pipes the file through itself, for every 1Mb file it only uses ~0.1Mb of memory with the default block size
*/
// #region File Encryption
public function encryptFile(string $fileInput, string $fileOutput, bool $integrity_check = TRUE) {
@@ -193,8 +207,42 @@ class kpcrypt {
return 1;
}
/**
* @param string $fileInput The path to the encrypted file we want to decrypt
* @param string $fileOutput The path to where to place the decrypted content
*/
public function decryptFile(string $fileInput, string $fileOutput) {
// Try and open the destionation
if ( $fout = fopen($fileOutput, 'w') ) {
// Try and open the input file
if ($fin = fopen($fileInput, 'rb') ) {
// Get the IV from the beginning of the file
$iv = fread($fin, openssl_cipher_iv_length($this->cipherMethod));
while (!feof($fin)) {
// we have to read one block more for decrypting than for encrypting
$ciphertext = fread($fin, 16 * ($this->blocks + 1));
$plaintext = openssl_decrypt($ciphertext, $this->cipherMethod, $this->key, OPENSSL_RAW_DATA, $iv);
// Use the first 16 bytes of the ciphertext as the next initialization vector
$iv = substr($ciphertext, 0, 16);
fwrite($fout, $plaintext);
}
// Close the input file
fclose($fin);
} else {
$this->errorLog[] = "[" . __LINE__ . "]" . "Could not open file output path for writing.";
return false;
}
// Close the output file
fclose($fout);
return 1;
}
}
// #endregion