簡體   English   中英

PHP:使用openssl_encrypt加密文件

[英]PHP: Encrypt files using openssl_encrypt

有沒有一種方法可以使用openssl_encrypt加密整個文件(代碼)。 我找到了一個相關的線程 ,但是不知道如何轉換它。

我只需要一個簡單的代碼即可上手..

這是我要轉換的代碼。

<?php
$key = 'bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU=';

function my_encrypt($data, $key) {
    $encryption_key = base64_decode($key);
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
    return base64_encode($encrypted . '::' . $iv);
}

function my_decrypt($data, $key) {
    $encryption_key = base64_decode($key);
    list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
    return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
}

$password_plain = 'abc123';
echo $password_plain . "<br>";

$password_encrypted = my_encrypt($password_plain, $key);
echo $password_encrypted . "<br>";

$password_decrypted = my_decrypt($password_encrypted, $key);
echo $password_decrypted . "<br>"; 

希望你能幫到你。

謝謝。

您的加密和解密功能似乎正常工作。

您的代碼流應如下所示:

$code = file_get_contents('path/to/code.php'); //Get the code to be encypted.
$encrypted_code = my_encrypt($code, $key); //Encrypt the code.
echo 'Encrypted Code <br><br>';
echo $encrypted_code;

file_put_contents('path/to/save/encrypted_code.php', $encrypted_code); //Save the ecnypted code somewhere.

$encrypted_code = file_get_contents('path/to/save/encrypted_code.php'); //Get the encrypted code.
$decrypted_code = my_decrypt($encrypted_code, $key);//Decrypt the encrypted code.
echo 'Decrypted Code <br><br>';
echo $decrypted_code;

file_put_contents('path/to/save/code.php', $decrypted_code); //Save the decrypted code somewhere.

這只是一個非常基本的例子。

您還應該閱讀有關file_put_contents()其他參數。

確保您寫入的任何文件都具有適當的寫入權限,否則將無法保存該文件。 chmod()函數可用於操縱您的文件夾/文件權限。

我推薦的一個很好的加密庫是Libsodium 現在可以在PHP> = 7.2中使用。它是一個功能強大的加密庫。 你應該檢查一下。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM