Home > Backend Development > PHP Tutorial > How to encrypt/decrypt files using exclusive OR (XOR) via php

How to encrypt/decrypt files using exclusive OR (XOR) via php

jacklove
Release: 2023-03-31 10:30:02
Original
4793 people have browsed it

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 = &#39;test.jpg&#39;;
$encrypt_file = &#39;test_enc.jpg&#39;;
$decrypt_file = &#39;test_dec.jpg&#39;;
$key = &#39;D89475D32EA8BBE933DBD299599EEA3E&#39;;

echo &#39;<p>source:</p>&#39;;
echo &#39;<img src="&#39;.$source.&#39;" width="200">&#39;;
echo &#39;<hr>&#39;;

file_encrypt($source, $encrypt_file, $key); // encrypt

echo &#39;<p>encrypt file:</p>&#39;;
echo &#39;<img src="&#39;.$encrypt_file.&#39;" width="200">&#39;;
echo &#39;<hr>&#39;;

file_encrypt($encrypt_file, $decrypt_file, $key); // decrypt

echo &#39;<p>decrypt file:</p>&#39;;
echo &#39;<img src="&#39;.$decrypt_file.&#39;" width="200">&#39;;

/** 文件加密,使用key与原文异或生成密文,解密则再执行一次异或即可
* @param String $source 要加密或解密的文件
* @param String $dest   加密或解密后的文件
* @param String $key    密钥
*/
function file_encrypt($source, $dest, $key){
	if(file_exists($source)){
		
		$content = &#39;&#39;;          // 处理后的字符串
		$keylen = strlen($key); // 密钥长度
		$index = 0;

		$fp = fopen($source, &#39;rb&#39;);

		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;
	}
}

?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template