Home > Article > Backend Development > How to encrypt/decrypt files using exclusive OR (XOR) via php
php Use XOR (XOR) to encrypt/decrypt files
Principle: perform a bitwise XOR operation on each byte of the file and the key (XOR), decryption will perform an XOR operation again.
The code is as follows:
<?php $source = 'test.jpg'; $encrypt_file = 'test_enc.jpg'; $decrypt_file = 'test_dec.jpg'; $key = 'D89475D32EA8BBE933DBD299599EEA3E'; echo '<p>source:</p>'; echo '<img src="'.$source.'" width="200">'; echo '<hr>'; file_encrypt($source, $encrypt_file, $key); // encrypt echo '<p>encrypt file:</p>'; echo '<img src="'.$encrypt_file.'" width="200">'; echo '<hr>'; file_encrypt($encrypt_file, $decrypt_file, $key); // decrypt echo '<p>decrypt file:</p>'; echo '<img src="'.$decrypt_file.'" width="200">'; /** 文件加密,使用key与原文异或生成密文,解密则再执行一次异或即可 * @param String $source 要加密或解密的文件 * @param String $dest 加密或解密后的文件 * @param String $key 密钥 */ function file_encrypt($source, $dest, $key){ if(file_exists($source)){ $content = ''; // 处理后的字符串 $keylen = strlen($key); // 密钥长度 $index = 0; $fp = fopen($source, 'rb'); while(!feof($fp)){ $tmp = fread($fp, 1); $content .= $tmp ^ substr($key,$index%$keylen,1); $index++; } fclose($fp); return file_put_contents($dest, $content, true); }else{ return false; } } ?>
This article introduces how to use heterogeneity through php Or (XOR) encrypt/decrypt files, please pay attention to php Chinese website for more related content.
Related recommendations:
How to get the name of a variable through PHP
Learn about PHP object cloning clone
About mysql general log related operations
The above is the detailed content of How to encrypt/decrypt files using exclusive OR (XOR) via php. For more information, please follow other related articles on the PHP Chinese website!