如何使用php加密大文件并通过命令行解密?

Mat*_*kel 5 php linux encryption cryptography mcrypt

我正在用PHP编写一个小脚本来备份我的文件.在我从服务器传输文件之前,我想加密它们.

我在我的脚本的早期版本中通过在我的Linux服务器上使用exec()和OpenSSL来做到这一点.现在我正在寻找一个本机PHP函数来完成这项工作,主要是为了更好的错误处理.

问题是我的文件可能变大(如20gb).此外,我必须在shell上使用命令再次解密文件.

有谁知道如何加密PHP中的大文件,然后在命令行解密?

我现在正在使用PHP的mcrypt函数来加密:

// IV:
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);

// Create new random Key:
$key = openssl_random_pseudo_bytes(32);

// Encrypt:
$fileStream = fopen($file, "r");
$encFileStream = fopen($file . ".enc.data", "w");

$opts = [
    'iv'   => $iv,
    'key'  => $key,
    'mode' => 'cbc'
];
stream_filter_append($encFileStream, 'mcrypt.rijndael-256', STREAM_FILTER_WRITE, $opts);
stream_copy_to_stream($fileStream, $encFileStream);

fclose($fileStream);
fclose($encFileStream);

// Encrypt random generated key and save it:
$encryptedKey = null;
openssl_public_encrypt($key, $encryptedKey, $publickey);
file_put_contents($file . ".enc.key", $encryptedKey);

// Save Initial Vetor:
file_put_contents($file . ".enc.iv", $iv);

// Delete unencrypted file:
unlink($file);
Run Code Online (Sandbox Code Playgroud)

现在要在linux命令行上解密我也尝试使用mcrypt.但我遇到的最大问题是我不知道如何添加IV mdecrypt.到目前为止,我的命令是:

mdecrypt --decrypt -m CBC -f key.key archive_hallo.tar.gz.enc.data
Run Code Online (Sandbox Code Playgroud)

这当然不起作用,因为缺少IV.那么,有没有人知道如何将IV添加到我的mdecrypt命令中

osg*_*sgx 3

mdecryptmcrypt_2.6.8 debian 软件包中的 CLI 工具需要带有 header 的特定文件格式。搜索write_file_head函数,显示mcrypt/mdecrypt工具格式的前3个字节:

buf[0] = '\0';
buf[1] = 'm';
buf[2] = '\3';
Run Code Online (Sandbox Code Playgroud)

标头应设置特殊位,并将 IV 嵌入到文件中。它将在此处读取,在decrypt_general函数中:

if (_mcrypt_iv_is_needed(td, mode, noiv) != 0) {
   IV = read_iv(FROMF, mcrypt_enc_get_iv_size(td));
} else {
   IV = _mcrypt_calloc(1, mcrypt_enc_get_iv_size(td));
}
Run Code Online (Sandbox Code Playgroud)

在extra.cread_iv中定义为:

void *read_iv(FILE * fstream, int ivsize)
{
char *IV;
     ... // malloc 
fread(IV, 1, ivsize, fstream);
    return IV;
}
Run Code Online (Sandbox Code Playgroud)

因此,只需检查加密文件的前 N ​​个字节(您可以在 后将它们发布到此处hexdump -C)并检查 mcrypt 标头(0x00 'm' 0x03)和您的 IV。如果是 - 那么mdecrypt工具应该从文件中获取 IV。如果不是 - 不支持通过命令行设置 IV mdecrypt,但您可以侵入源代码,为 iv 添加新选项,然后修改decrypt_general以从选项读取 iv。