PHP Data compression, encryption and decryption (pack, unpack)

Source: Internet
Author: User
Tags flock unpack
Data is frequently exchanged in network communication and file storage. to reduce network communication traffic, file storage size, and encrypted communication rules, two-way encryption and decryption of data is often required to ensure data security. The main functions required to implement this function in PHP are pack and unpack function pack. Syntax: stringpack (stringformat, mixed [args] network communication and file storage often need to exchange data. to reduce network communication traffic, file storage size, and encrypted communication rules, it is often necessary to encrypt and decrypt data in two ways to ensure data security.

The main functions required to implement this function in PHP are pack and unpack functions.

Pack

The compressed data is in the string.

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

Return value: string

This function is used to compress and package data into strings.

A-NUL-string fills up [padded string] to fill the blank string with NULL characters

A-SPACE-string filling [padded string]

H-hexadecimal string, with a low "four-digit" [low nibble first] (before low position)

H-hexadecimal string, high "four-digit" [high nibble first] (high front)

C-signed characters

C-non-symbolic characters

S-signed short mode [short] (usually 16 bits, in machine byte order)

S-unsigned short mode [short] (usually 16 bits, sorted by machine bytes)

N-unsigned short mode [short] (usually 16 bits, sorted by large endian bytes)

V-short mode without symbols [short] (usually 16 bits, sorted by small endian bytes)

I-signed integer (determined by the size and byte order)

I-unsigned integer (determined by the size and byte order)

L-signed long mode [long] (usually 32-bit, in the byte order of the machine)

L-long mode without symbols [long] (usually 32-bit, in the byte order of the machine)

N-long mode without symbols [long] (usually 32-bit, in the order of large edian bytes)

V-long mode without symbols [long] (usually 32-bit, in the small edian byte order)

F-floating point (determined by the size and byte sequence)

D-double precision (determined by the size and byte order)

X-null byte [NUL byte]

X-the next byte [Back up one byte] (returns one byte)

Unpack

Extract the bit string.

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

Returned value: Array

This function is used to extract the data of a bit string. The functions of this function and Perl functions with the same name have the same usage.

Case 1: pack to reduce the file data storage size

 


The file size of ipvtest.txt is 10 bytes. Note that the file size is 10 bytes and the actual occupied space is 1 kB.

The entire number of bytes stored is stored in the test.txt file in serial form.

However, if you store the jy string as an integer, it will be reduced to 4 bytes.

  


Case 2: Data Encryption

Store a piece of meaningful data as a string, 7-110-abcdefg-117.

After the character "-" is separated, the first character indicates the string length, the second character indicates the storage position, the third character indicates the actually stored string, and the fourth character indicates the end position.

   

Disadvantages of the above method:
I. data storage size

2. data is stored in plain text. any sensitive information may cause insecure access.

III. file storage size, increasing in irregular mode.

Encryption:

    

Store a piece of data. the encryption format is: integer 2-bit length string 10-bit length integer 1-bit length.

Advantages:

I. data size optimization

2. if you do not know the compression format like "i2a7i1", even if you get the file, you cannot correctly read the binary file and convert it to plain text.

3. when data is increased, the file storage size increases proportionally. Each time it is increased by a 19byte.

Case 3: key-value type file storage

Two files are generated: index files and data files.

The format of data storage in the file is as follows:

     _ Node_struct = array ('next' => array (1, 'V'), 'prev' => array (1, 'V '), 'data _ offset '=> array (1, 'V'), // data storage start position 'data _ size' => array (1, 'V '), // data length 'ref _ count' => array (1, 'V'), // reference here, simulate the PHP reference counting destruction mode 'key' => array (16, 'H * '), // store the 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 +"); // binary storage needs to use B} // create the index file private function _ create_index () {$ this-> _ file_index = fopen ($ this-> _ file_index_name, "wb +"); // binary storage requires the use of B if (! $ This-> _ file_index) throw new fileCacheException ("cocould't open index file :". $ this-> _ file_index_name); $ this-> _ index_puts (0, '<'. '? Php exit ()? '. '>'); // Locate the file stream to the starting position 0, place the php mark to prevent downloading $ this-> _ index_puts ($ this-> _ file_header_size, pack ("V1 ", 0);} // create the storage file private function _ create_data () {$ this-> _ file_data = fopen ($ this-> _ file_data_name, "wb + "); // binary storage requires the use of B if (! $ This-> _ file_index) throw new fileCacheException ("cocould't open index file :". $ this-> _ file_data_name); $ this-> _ data_puts (0, '<'. '? Php exit ()? '. '>'); // Locate the file stream to the starting position 0, place the php mark to prevent downloading} 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);}/*** file lock * @ param $ is_block: exclusive or blocking lock */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 ($ t His-> _ 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 <$ index_count; $ 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) ;}// usage $ cache = new fileCache (); $ cache-> add ('abcdef', 'testabc'); $ data = $ cache-> get_node ('abcdefg'); print_r ($ data ); echo $ cache-> get_data ($ data ['data _ offset '], $ data ['data _ size']);



Case 4: socket communication encryption

Both parties define the encryption format:

For example:

$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()) );

The server and client locate the corresponding DATA decoding method based on the parsing COMMAND format to obtain the correct DATA

The above is a detailed description of PHP Data compression, encryption and decryption (pack, unpack) content, for more information, please follow the PHP Chinese network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.