zoukankan      html  css  js  c++  java
  • php 使用异或(XOR)加密/解密文件

    php 使用异或(XOR)加密/解密文件

    原理:将文件每一个字节与key作位异或运算(XOR),解密则再执行一次异或运算。


    代码如下:

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

    相关文章:《C 使用异或(xor)加密/解密文件》



  • 相关阅读:
    PyTorch深度学习:60分钟入门(Translation)
    强化学习入门·
    leetcode 697. Degree of an Array
    耶路撒冷圣城起源笔记
    仓储机器人路径规划笔记
    算术编码原理
    ★房贷计算器 APP
    Sublime
    CocoaPods
    Xcode 6 创建 Objective-C category
  • 原文地址:https://www.cnblogs.com/fdipzone/p/3715078.html
Copyright © 2011-2022 走看看