请看这篇文档 PHP可逆密码加密例程,它适用于那些想要一个可逆的密码加密例程的PHP开发人员。
虽然该类是用于密码加密,但也可以用于任何文本的加密/解密。
function encryption_class() {
$this->errors = array();
// Each of these two strings must contain the same characters, but in a different order.
// Use only printable characters from the ASCII table.
// Do not use single quote, double quote or backslash as these have special meanings in PHP.
// Each character can only appear once in each string.
$this->scramble1 = '! #$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$this->scramble2 = 'f^jAE]okIOzU[2&q1{3`h5w_794p@6s8?BgP>dFV=m D<TcS%Ze|r:lGK/uCy.Jx)HiQ!#$~(;Lt-R}Ma,NvW+Ynb*0X';
if (strlen($this->scramble1) <> strlen($this->scramble2)) {
trigger_error('** SCRAMBLE1 is not same length as SCRAMBLE2 **', E_USER_ERROR);
} // if
$this->adj = 1.75; // this value is added to the rolling fudgefactors
$this->mod = 3; // if divisible by this the adjustment is made negative
}
注意:
如果您使用的是PHP版本>= 5.3.3,则必须将类名从encryption_class
更改为__construct
原因:
自PHP 5.3.3以来,具有与命名空间类名称的最后一个元素相同名称的方法将不再被视为构造函数。
用法:
$crypt = new encryption_class();
$crypt->setAdjustment(1.75); // 1st adjustment value (optional)
$crypt->setModulus(3); // 2nd adjustment value (optional)
/**
*
* @param string $key - Your encryption key
* @param string $sourceText - The source text to be encrypted
* @param integer $encLen - positive integer indicating the minimum length of encrypted text
* @return string - encrypted text
*/
$encrypt_result = $crypt->encrypt($key, $sourceText, $encLen);
/**
*
* @param string $key - Your encryption key (same used for encryption)
* @param string $encrypt_result - The text to be decrypted
* @return string - decrypted text
*/
$decrypt_result = $crypt->decrypt($key, $encrypt_result);
更新:
上面的类不是用来加密文件的,但是你可以使用以下步骤进行加密:
base64_encode
源文本(文件内容)
- 对于实际加密,将上述加密/解密类应用于 base64 编码的文本
- 对于解密,将上述加密/解密类应用于实际加密的文本
base64_decode
将给出实际文件内容(您可以使用此内容保存文件的副本)
我已经加密了一张图片,解密并保存到了一个新文件中!!! 查看代码。
require 'class.encryption.php';
$key = 'This is my secret key; with symbols (@$^*&<?>/!#_+), cool eh?!!! :)';
$adjustment = 1.75;
$modulus = 2;
$sourceFileName = 'source-image.png';
$destFileName = 'dest-image.png';
$minSpecifiedLength = 512;
$sourceText = base64_encode(file_get_contents($sourceFileName));
$crypt = new encryption_class();
$crypt->setAdjustment($adjustment);
$crypt->setModulus($modulus);
$encrypt_result = $crypt->encrypt($key, $sourceText, $minSpecifiedLength);
$decrypt_result = base64_decode($crypt->decrypt($key, $encrypt_result));
file_put_contents($destFileName, $decrypt_result);