Рубрики
Uncategorized

PHP реализует симметричное шифрование и дешифрование изображений (подходит для таких сценариев, как шифрование идентификационных карт)

Автор оригинала: David Wong.

Шифрование и дешифрование изображений

Изображения удостоверений личности персонала могут быть зашифрованы путем изменения байтов, и информация об удостоверениях личности также может быть записана в изображения. Следующий код можно напрямую скопировать в PHP – файл для тестирования. Подробности см. в коде.

php

/***
 *                    .::::.
 *                  .::::::::.
 *                 :::::::::::  FUCK YOU
 *             ..:::::::::::'
 *           '::::::::::::'
 *             .::::::::::
 *        '::::::::::::::..
 *             ..::::::::::::.
 *           ``::::::::::::::::
 *            ::::``:::::::::'        .:::.
 *           ::::'   ':::::'       .::::::::.
 *         .::::'      ::::     .:::::::'::::.
 *        .:::'       :::::  .:::::::::' ':::::.
 *       .::'        :::::.:::::::::'      ':::::.
 *      .::'         ::::::::::::::'         ``::::.
 *  ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 *                    '.:::::'                    ':'````..
 */

class Encrypt 
{
    
    /**
     * Symmetric Encryption of Pictures
     *
     *@ Param [string] $filePath image path
     * @return void
     */
    public function enc($filePath)
    {
        // Document recommendation: For portability, it is strongly recommended to always use the'b'tag when opening a file with fopen ().
        $fileId = fopen($filePath, 'rb+');

        // Number of bytes taken out of the file size (29124)
        $fileSize = fileSize($filePath);

        // Read the file and return the read string (read out as a binary sequence)
        $img = fread($fileId, $fileSize);

        // Unpackage data from binary strings using unsigned characters
        // (pack, unpack usage) https://segmentfault.com/a/1190000008305573
        $imgUnpack = unpack ('C*', $img); one-dimensional array of // $fileSize length [1 = > 255, 2 = > 216, 3 = > 255,...] 29124=>217]
        
        // Close an open file pointer        
        fclose($fileId);

        $tempArr = [];
        // Custom Encryption Rules
        for ($i = 1; $i <= $fileSize; $i++) { 
            $value = 0;
            if ($i % 3 == 0) {
                $value = 2;
            } elseif ($i % 5 == 0) {
                $value = 4;
            } elseif ($i % 7 == 0) {
                $value = 6;
            }
            $byte = $imgUnpack [$i]; // Picture original bytes
            $byte = $byte + $value; // bytes after encryption rules
            // Packed into binary strings
            $tempArr[] = pack('C*', $byte);
        }

        $img = implode (', $tempArr); // Replace the one-dimensional assembly after unpacking with a string
        File_put_contents ($filePath, $img); // Rewrite the picture
    }


    /**
     * Symmetric Decryption of Pictures
     *
     *@ Param [string] $filePath image path
     * @return void
     */
    public function dec($filePath)
    {
        $fileId = fopen($filePath, 'rb+');
        $fileSize = filesize($filePath);
        $img = fread($fileId, $fileSize);
        $imgUnpack = unpack('C*', $img);
        fclose($fileId);

        $tempArr = [];
        // Start decrypting
        for ($i = 1; $i <= $fileSize; $i++) { 
            $value = 0;
            if ($i % 3 == 0) {
                $value = 2;
            } elseif ($i % 5 == 0) {
                $value = 4;
            } elseif ($i % 7 == 0) {
                $value = 6;
            }
            $byte = $imgUnpack[$i];
            $byte = $byte - $value;
            $tempArr[] = pack('C*', $byte);
        }
        $img = implode('', $tempArr);
        file_put_contents($filePath, $img);
    }


    /**
     * Picture Additional Information
     *
     *@ Param [string] $filePath image path
     *@ Param [array] $cardmsg needs to add an array of information
     *@ Param [array] $separate delimited array (similar to making an encryption delimited key)
     * @return void
     */
    public function encmsg($filePath, $cardmsg, $separate)
    {
        // Document recommendation: For portability, it is strongly recommended to always use the'b'tag when opening a file with fopen ().
        $fileId = fopen($filePath, 'rb+');
        // Number of bytes taken out of the file size (29124)
        $fileSize = fileSize($filePath);
        // Read the file and return the read string (read out as a binary sequence)
        $img = fread($fileId, $fileSize);
        // Unpackage data from binary strings using unsigned characters
        // (pack, unpack usage) https://segmentfault.com/a/1190000008305573
        $imgUnpack = unpack ('C*', $img); one-dimensional array of // $fileSize length [1 = > 255, 2 = > 216, 3 = > 255,...] 29124=>217]
        // Close an open file pointer        
        fclose($fileId);

        // Processing identity information
        $cardmsgJson = json_encode($cardmsg, JSON_UNESCAPED_UNICODE);
        $cardmsgUnpack = unpack('C*', $cardmsgJson);

        // Merge image bytes, customized segregated arrays (similar to manual plus key values), identity bytes
        $mergeArr = array_merge($imgUnpack, $separate, $cardmsgUnpack);

        $pack = [];
        foreach ($mergeArr as $k => $v) {
            $pack[] = pack('C*', $v);
        }
        $packStr = join('', $pack);
        File_put_contents ($filePath, $packStr); // Rewrite the picture
    }


    /**
     * Get information about additional pictures
     *
     *@ Param [string] $filePath image path
     *@ Separated array defined by param [array] $separate (Separated key)
     *@ Additional picture information to return [string]
     */
    public function decmsg ($filePath, $separate) 
    {
        // Document recommendation: For portability, it is strongly recommended to always use the'b'tag when opening a file with fopen ().
        $fileId = fopen($filePath, 'rb+');
        // Number of bytes taken out of file size (29192)
        $fileSize = fileSize($filePath);
        // Read the file and return the read string (read out as a binary sequence)
        $img = fread($fileId, $fileSize);

        // Unpackage data from binary strings using unsigned characters
        $imgUnpack = unpack ('C*', $img); one-dimensional array of // $fileSize length [1 = > 255, 2 = > 216, 3 = > 255,...] 29192=>217]
        // Close an open file pointer        
        fclose($fileId);

        $imgUnpackStr = join (',', $imgUnpack); // Converts a one-dimensional array to a string
        $separateStr = implode (',', $separate);// Converts a one-dimensional array to a string
        $imgAndCardmsgArr = explode ($separateStr, $imgUnpackStr); // Separate image bytes and identity bytes with custom delimiters
        
        $cardmsgArr = explode (',', $imgAndCardmsgArr [1]); // Take out identity information bytes
        Unset ($cardmsgArr [0]); // / Remove the first blank of the identity information byte (left when the string rotates the array)
        $cardmsg = '';
        foreach ($cardmsgArr as $k => $v) {
            $cardmsg. = pack ('C*', $v); // packaged into binary file strings
        }
 
        return json_decode($cardmsg, true);
    }



}


$encrypt = new Encrypt();

$path = './001.jpg';

$separate = [255, 0, 255, 0, 255, 0, 255, 206, 210, 202, 199, 183, 214, 184, 244]; //15 bytes
$cardmsg = ['name'=>'Zhang San','gender'=>'man','idcard'=> 12345678910]; //53 bytes