一個略高效的自制加解密函數

<?php
/**
 * Crypt class file.
 * 
 * @author woondroo
 * @package framework
 * @date 2015-04-09
 */
class Crypt
{
    /**
     * Passport 加密函數
     *
     * @param    string     等待加密的原字串
     * @param    string     私有密匙(用於解密和加密)
     *
     * @return    string     原字串通過私有密匙加密後的結果
     */
    public static function encode( $_strVal = "" , $_strKey = "" )
    {
        // 使用隨機數發生器產生 0~32000 的值並 MD5()
        srand((double)microtime() * 1000000);
        $encrypt_key = md5(rand(0, 32000));php

        // 變量初始化
        $ctr = 0;
        $tmp = '';函數

        // for 循環,$i 爲從 0 開始,到小於 $_strVal 字串長度的整數
        for($i = 0; $i < strlen($_strVal); $i++)
        {
            // 若是 $ctr = $encrypt_key 的長度,則 $ctr 清零
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            // $tmp 字串在末尾增長兩位,其第一位內容爲 $encrypt_key 的第 $ctr 位,
            // 第二位內容爲 $_strVal 的第 $i 位與 $encrypt_key 的 $ctr 位取異或。而後 $ctr = $ctr + 1
            $tmp .= $encrypt_key[$ctr].($_strVal[$i] ^ $encrypt_key[$ctr++]);
        }編碼

        // 返回結果,結果爲 passport_key() 函數返回值的 base65 編碼結果
        return base64_encode(self::doOp($tmp, $_strKey));加密

    }.net

    /**
     * Passport 解密函數
     *
     * @param    string     加密後的字串
     * @param    string     私有密匙(用於解密和加密)
     *
     * @return    string     字串通過私有密匙解密後的結果
     */
    public static function decode( $_strVal = "" , $_strKey = "" )
    {code

        // $_strVal 的結果爲加密後的字串通過 base64 解碼,而後與私有密匙一塊兒,
        // 通過 passport_key() 函數處理後的返回值
        $_strVal = self::doOp(base64_decode($_strVal), $_strKey);md5

        // 變量初始化
        $tmp = '';get

        // for 循環,$i 爲從 0 開始,到小於 $_strVal 字串長度的整數
        for ($i = 0; $i < strlen($_strVal); $i++)
        {
            // $tmp 字串在末尾增長一位,其內容爲 $_strVal 的第 $i 位,
            // 與 $_strVal 的第 $i + 1 位取異或。而後 $i = $i + 1
            $tmp .= $_strVal[$i] ^ $_strVal[++$i];
        }string

        // 返回 $tmp 的值做爲結果
        return $tmp;io

    }

    /**
     * Passport 密匙處理函數
     *
     * @param    string     待加密或待解密的字串
     * @param    string     私有密匙(用於解密和加密)
     *
     * @return    string     處理後的密匙
     */
    public static function doOp( $_strVal = "" , $_strKey = "" )
    {    
        // 將 $encrypt_key 賦爲 $encrypt_key 經 md5() 後的值
        $strKey = md5( $_strKey );

        // 變量初始化
        $ctr = 0;
        $tmp = '';

        // for 循環,$i 爲從 0 開始,到小於 $_strVal 字串長度的整數
        for($i = 0; $i < strlen($_strVal); $i++) {
            // 若是 $ctr = $encrypt_key 的長度,則 $ctr 清零
            $ctr = $ctr == strlen($strKey) ? 0 : $ctr;
            // $tmp 字串在末尾增長一位,其內容爲 $_strVal 的第 $i 位,
            // 與 $encrypt_key 的第 $ctr + 1 位取異或。而後 $ctr = $ctr + 1
            $tmp .= $_strVal[$i] ^ $strKey[$ctr++];
        }

        // 返回 $tmp 的值做爲結果
        return $tmp;
    }

//end class }

相關文章
相關標籤/搜索