首頁 php教程 php手册 PHP数据压缩、加解密(pack, unpack)

PHP数据压缩、加解密(pack, unpack)

Jun 13, 2016 am 10:55 AM
php 為了 交換 壓縮 儲存 數據 文件 網路通訊 解密 需要

网络通信、文件存储中经常需要交换数据,为了减少网络通信流量、文件存储大小以及加密通信规则,经常需要对数据进行双向加解密以保证数据的安全。

PHP中实现此功能主要需要使用的函数主要是pack及unpack函数

 

 

pack

压缩资料到位字符串之中。

 

语法: string pack(string format, mixed [args]...);

 

返回值: 字符串

本函数用来将资料压缩打包到位的字符串之中。

 

 

a - NUL- 字符串填满[padded string] 将字符串空白以 NULL 字符填满

A - SPACE- 字符串填满[padded string]

h – 十六进制字符串,低“四位元”[low nibble first] (低位在前)

H - 十六进制字符串,高“四位元”[high nibble first](高位在前)

c – 带有符号的字符

C – 不带有符号的字符

s – 带有符号的短模式[short](通常是16位,按机器字节顺序)

S – 不带有符号的短模式[short](通常是16位,按机器字节排序)

n -不带有符号的短模式[short](通常是16位,按大endian字节排序)

v -不带有符号的短模式[short](通常是16位,按小endian字节排序)

i – 带有符号的整数(由大小和字节顺序决定)

I – 不带有符号的整数(由大小和字节顺序决定)

l– 带有符号的长模式[long](通常是32位,按机器字节顺序)

L – 不带有符号的长模式[long](通常是32位,按机器字节顺序)

N – 不带有符号的长模式[long](通常是32位,按大edian字节顺序)

V– 不带有符号的长模式[long](通常是32位,按小edian字节顺序)

f –浮点(由大小和字节顺序决定)

d – 双精度(由大小和字节顺序决定)

x – 空字节[NUL byte]

X- 后面一个字节[Back up one byte](倒回一位)

 

 

 

 

unpack

 

解压缩位字符串资料。

 

语法: string pack(string format, mixed [args]...);

 

返回值: 数组

本函数用来将位的字符串的资料解压缩。本函数和 Perl 的同名函数功能用法完全相同。

 

 

案例一、pack实现缩减文件数据存储大小

[php]

//存储整数1234567890   

file_put_contents("test.txt", 1234567890);  

 

//存储整数1234567890

file_put_contents("test.txt", 1234567890);此时test.txt的文件大小是10byte。注意此时文件大小是10字节,实际占用空间大小是1KB。

 

 

 

上面存储的整数实际是以字符串形式存储于文件test.txt中。

但如果以整数的二进制字符串存jy储,将会缩减至4byte。

 

[php] 

print_r(unpack("i", file_get_contents("test.txt")));  

 

print_r(unpack("i", file_get_contents("test.txt")));

 

 

 

 

 

 

案例二、数据加密

以字符串形式存储一段有意义数据,7-110-abcdefg-117。

字符"-"分割后,第一位表示字符串长度,第二位表示存储位置,第三位表示实际存储的字符串,第四位表示结尾位置。

[php] 

file_put_contents("test.txt", "7-110-abcdefg-117");  

 

file_put_contents("test.txt", "7-110-abcdefg-117");

上述方法缺点:

一、数据存储大小

二、数据以明文方式存储,如果是任何敏感信息,都可能造成不安全访问。

三、文件存储大小,以不规则方式递增。

 

 

加密:

[php] 

file_put_contents("test.txt", pack("i2a7i1", 7, 110, "abcdefg", 117));  

 

file_put_contents("test.txt", pack("i2a7i1", 7, 110, "abcdefg", 117));

存储一段数据,加密格式为:整数2位长度字符串10位长度整数1位长度。

优点:

一、数据大小最优化

二、在不知道"i2a7i1"这样的压缩格式时,即使拿到文件,也无法正确读出二进制文件转化为明文。

三、数据增加时,文件存储大小是等量递增。每次都是以19byte递增。

 

 

案例三、key-value型文件存储www.2cto.com

存储生成的文件为两个:索引文件,数据文件

文件中数据存储的格式如下图:

 

代码实现:

[php]

error_reporting(E_ALL);  

  

class fileCacheException extends Exception{  

  

}  

  

//Key-Value型文件存储   

class fileCache{  

     private $_file_header_size = 14;  

     private $_file_index_name;  

     private $_file_data_name;  

     private $_file_index;//索引文件句柄   

     private $_file_data;//数据文件句柄   

     private $_node_struct;//索引结点结构体   

     private $_inx_node_size = 36;//索引结点大小   

  

     public function __construct($file_index="filecache_index.dat", $file_data="filecache_data.dat"){  

          $this->_node_struct = array(  

               'next'=>array(1, 'V'),  

               'prev'=>array(1, 'V'),  

              'data_offset'=>array(1,'V'),//数据存储起始位置   

              'data_size'=>array(1,'V'),//数据长度   

              'ref_count'=>array(1,'V'),//引用此处,模仿PHP的引用计数销毁模式   

              'key'=>array(16,'H*'),//存储KEY   

          );  

  

          $this->_file_index_name = $file_index;  

          $this->_file_data_name = $file_data;  

  

          if(!file_exists($this->_file_index_name)){  

               $this->_create_index();  

          }else{  

               $this->_file_index = fopen($this->_file_index_name, "rb+");  

          }  

  

          if(!file_exists($this->_file_data_name)){  

               $this->_create_data();  

          }else{  

               $this->_file_data = fopen($this->_file_data_name, "rb+");//二进制存储需要使用b   

          }  

     }  

  

     //创建索引文件   

     private function _create_index(){  

          $this->_file_index = fopen($this->_file_index_name, "wb+");//二进制存储需要使用b   

          if(!$this->_file_index)   

               throw new fileCacheException("Could't open index file:".$this->_file_index_name);  

  

          $this->_index_puts(0, '');//定位文件流至起始位置0, 放置php标记防止下载   

          $this->_index_puts($this->_file_header_size, pack("V1", 0));  

     }  

  

  

     //创建存储文件   

     private function _create_data(){  

          $this->_file_data = fopen($this->_file_data_name, "wb+");//二进制存储需要使用b   

          if(!$this->_file_index)   

               throw new fileCacheException("Could't open index file:".$this->_file_data_name);  

  

          $this->_data_puts(0, '');//定位文件流至起始位置0, 放置php标记防止下载   

     }  

  

     private function _index_puts($offset, $data, $length=false){  

          fseek($this->_file_index, $offset);  

  

          if($length)  

          fputs($this->_file_index, $data, $length);  

          else  

          fputs($this->_file_index, $data);  

     }  

  

     private function _data_puts($offset, $data, $length=false){  

          fseek($this->_file_data, $offset);  

          if($length)  

          fputs($this->_file_data, $data, $length);  

          else  

          fputs($this->_file_data, $data);  

     }  

  

     /** 

     * 文件锁 

     * @param $is_block 是否独占、阻塞锁 

     */  

     private function _lock($file_res, $is_block=true){  

          flock($file_res, $is_block ? LOCK_EX : LOCK_EX|LOCK_NB);  

     }  

  

     private function _unlock($file_res){  

          flock($file_res, LOCK_UN);  

     }  

  

     public function add($key, $value){  

          $key = md5($key);  

          $value = serialize($value);  

          $this->_lock($this->_file_index, true);  

          $this->_lock($this->_file_data, true);  

  

          fseek($this->_file_index, $this->_file_header_size);  

  

          list(, $index_count) = unpack('V1', fread($this->_file_index, 4));  

  

          $data_size = filesize($this->_file_data_name);  

  

          fseek($this->_file_data, $data_size);  

  

          $value_size = strlen($value);  

  

          $this->_data_puts(filesize($this->_file_data_name), $value);  

  

          $node_data =   

          pack("V1V1V1V1V1H32", ($index_count==0) ? 0 : $index_count*$this->_inx_node_size, 0, filesize($this->_file_data_name), strlen($value), 0, $key);  

  

          $index_count++;  

  

          $this->_index_puts($this->_file_header_size, $index_count, 4);  

  

          $this->_index_puts($this->get_new_node_pos($index_count), $node_data);  

  

          $this->_unlock($this->_file_data);  

          $this->_unlock($this->_file_index);  

     }  

  

     public function get_new_node_pos($index_count){  

          return $this->_file_header_size + 4 + $this->_inx_node_size * ($index_count-1);  

     }  

  

     public function get_node($key){  

          $key = md5($key);  

          fseek($this->_file_index, $this->_file_header_size);  

          $index_count = fread($this->_file_index, 4);  

  

          if($index_count>0) {  

               for ($i=0; $i

                    fseek($this->_file_index, $this->_file_header_size + 4 + $this->_inx_node_size * $i);  

                    $data = fread($this->_file_index, $this->_inx_node_size);  

                    $node = unpack("V1next/V1prev/V1data_offset/V1data_size/V1ref_count/H32key", $data);  

  

                    if($key == $node['key']){  

                         return $node;  

                    }  

               }  

          }else{  

               return null;  

          }  

     }  

  

     public function get_data($offset, $length){  

          fseek($this->_file_data, $offset);  

          return unserialize(fread($this->_file_data, $length));  

     }  

}  

  

//使用方法   

$cache = new fileCache();  

$cache->add('abcdefg' , 'testabc');  

$data = $cache->get_node('abcdefg');  

print_r($data);  

echo $cache->get_data($data['data_offset'], $data['data_size']);  

 

error_reporting(E_ALL);

 

class fileCacheException extends Exception{

 

}

 

//Key-Value型文件存储

class fileCache{

     private $_file_header_size = 14;

     private $_file_index_name;

     private $_file_data_name;

     private $_file_index;//索引文件句柄

     private $_file_data;//数据文件句柄

     private $_node_struct;//索引结点结构体

     private $_inx_node_size = 36;//索引结点大小

 

     public function __construct($file_index="filecache_index.dat", $file_data="filecache_data.dat"){

          $this->_node_struct = array(

               'next'=>array(1, 'V'),

               'prev'=>array(1, 'V'),

              'data_offset'=>array(1,'V'),//数据存储起始位置

              'data_size'=>array(1,'V'),//数据长度

              'ref_count'=>array(1,'V'),//引用此处,模仿PHP的引用计数销毁模式

              'key'=>array(16,'H*'),//存储KEY

          );

 

          $this->_file_index_name = $file_index;

          $this->_file_data_name = $file_data;

 

          if(!file_exists($this->_file_index_name)){

               $this->_create_index();

          }else{

               $this->_file_index = fopen($this->_file_index_name, "rb+");

          }

 

          if(!file_exists($this->_file_data_name)){

               $this->_create_data();

          }else{

               $this->_file_data = fopen($this->_file_data_name, "rb+");//二进制存储需要使用b

          }

     }

 

     //创建索引文件

     private function _create_index(){

          $this->_file_index = fopen($this->_file_index_name, "wb+");//二进制存储需要使用b

          if(!$this->_file_index) 

               throw new fileCacheException("Could't open index file:".$this->_file_index_name);

 

          $this->_index_puts(0, '');//定位文件流至起始位置0, 放置php标记防止下载

          $this->_index_puts($this->_file_header_size, pack("V1", 0));

     }

 

 

     //创建存储文件

     private function _create_data(){

          $this->_file_data = fopen($this->_file_data_name, "wb+");//二进制存储需要使用b

          if(!$this->_file_index) 

               throw new fileCacheException("Could't open index file:".$this->_file_data_name);

 

          $this->_data_puts(0, '');//定位文件流至起始位置0, 放置php标记防止下载

     }

 

     private function _index_puts($offset, $data, $length=false){

          fseek($this->_file_index, $offset);

 

          if($length)

          fputs($this->_file_index, $data, $length);

          else

          fputs($this->_file_index, $data);

     }

 

     private function _data_puts($offset, $data, $length=false){

          fseek($this->_file_data, $offset);

          if($length)

          fputs($this->_file_data, $data, $length);

          else

          fputs($this->_file_data, $data);

     }

 

     /**

     * 文件锁

     * @param $is_block 是否独占、阻塞锁

     */

     private function _lock($file_res, $is_block=true){

          flock($file_res, $is_block ? LOCK_EX : LOCK_EX|LOCK_NB);

     }

 

     private function _unlock($file_res){

          flock($file_res, LOCK_UN);

     }

 

     public function add($key, $value){

          $key = md5($key);

          $value = serialize($value);

          $this->_lock($this->_file_index, true);

          $this->_lock($this->_file_data, true);

 

          fseek($this->_file_index, $this->_file_header_size);

 

          list(, $index_count) = unpack('V1', fread($this->_file_index, 4));

 

          $data_size = filesize($this->_file_data_name);

 

          fseek($this->_file_data, $data_size);

 

          $value_size = strlen($value);

 

          $this->_data_puts(filesize($this->_file_data_name), $value);

 

          $node_data = 

          pack("V1V1V1V1V1H32", ($index_count==0) ? 0 : $index_count*$this->_inx_node_size, 0, filesize($this->_file_data_name), strlen($value), 0, $key);

 

          $index_count++;

 

          $this->_index_puts($this->_file_header_size, $index_count, 4);

 

          $this->_index_puts($this->get_new_node_pos($index_count), $node_data);

 

          $this->_unlock($this->_file_data);

          $this->_unlock($this->_file_index);

     }

 

     public function get_new_node_pos($index_count){

          return $this->_file_header_size + 4 + $this->_inx_node_size * ($index_count-1);

     }

 

     public function get_node($key){

          $key = md5($key);

          fseek($this->_file_index, $this->_file_header_size);

          $index_count = fread($this->_file_index, 4);

 

          if($index_count>0) {

               for ($i=0; $i

                    fseek($this->_file_index, $this->_file_header_size + 4 + $this->_inx_node_size * $i);

                    $data = fread($this->_file_index, $this->_inx_node_size);

                    $node = unpack("V1next/V1prev/V1data_offset/V1data_size/V1ref_count/H32key", $data);

 

                    if($key == $node['key']){

                         return $node;

                    }

               }

          }else{

               return null;

          }

     }

 

     public function get_data($offset, $length){

          fseek($this->_file_data, $offset);

          return unserialize(fread($this->_file_data, $length));

     }

}

 

//使用方法

$cache = new fileCache();

$cache->add('abcdefg' , 'testabc');

$data = $cache->get_node('abcdefg');

print_r($data);

echo $cache->get_data($data['data_offset'], $data['data_size']);

 

 

 

 

案例四、socket通信加密

通信双方都定义好加密格式:

例如:

[php] 

LOGIN = array(  

     'COMMAND'=>array('a30', 'LOGIN'),  

     'DATA'=>array('a30', 'HELLO')  

);  

  

$LOGOUT = array(  

     'COMMAND'=>array('a30', 'LOGOUT'),  

     'DATA'=>array('a30', 'GOOD BYE')  

);  

  

$LOGIN_SUCCESS = array(  

     'COMMAND'=>array('a30', 'LOGIN_SUCCESS'),  

     'DATA'=>array('V1', 1)  

);  

  

$LOGOUT_SUCCESS = array(  

     'COMMAND'=>array('a30', 'LOGIN_SUCCESS'),  

     'DATA'=>array('V1', time())  

);  

 

$LOGIN = array(

     'COMMAND'=>array('a30', 'LOGIN'),

     'DATA'=>array('a30', 'HELLO')

);

 

$LOGOUT = array(

     'COMMAND'=>array('a30', 'LOGOUT'),

     'DATA'=>array('a30', 'GOOD BYE')

);

 

$LOGIN_SUCCESS = array(

     'COMMAND'=>array('a30', 'LOGIN_SUCCESS'),

     'DATA'=>array('V1', 1)

);

 

$LOGOUT_SUCCESS = array(

     'COMMAND'=>array('a30', 'LOGIN_SUCCESS'),

     'DATA'=>array('V1', time())

);服务器端与客户端根据解析COMMAND格式,找到对应的DATA解码方式,得到正确的数据

 

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP與Python:了解差異 PHP與Python:了解差異 Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

PHP和Python:代碼示例和比較 PHP和Python:代碼示例和比較 Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP和Python:解釋了不同的範例 PHP和Python:解釋了不同的範例 Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

See all articles