自己寫一個Encode和Decode函數

來源:互聯網
上載者:User
<?php
/**
 *  * 用於字串的 URL 參數方式傳遞的編碼 encode
 *   */

//$sXorKey = "ckaua71/|&^$%!@9&#@&9237:;:""[[615kdhak";
$sXorKey = "ckaua71/|&^$%!@9&#@&9237:;:""[[61asdfsfd5kdha324@#!%adasfdafasdfk";

//$sPrivateKey = "fzja2qjdfasf_|`jau7z7cvja"";
$sPrivateKey = "fzja2qjdfasf_|`jau7z7cvjadfasfsafasfsadfasf343353453546fj7r89678a"";

function BinXorEncode($sInput) {
    global $sXorKey, $sPrivateKey;
    $sOut = $sInput ^ str_repeat($sXorKey, ceil(strlen($sInput)/strlen($sXorKey)));
    $sOut = pack("H*", md5($sOut.$sPrivateKey)).$sOut;
    $sOut = base64_encode($sOut);
    $sOut = str_replace("+", ",", $sOut);
    $sOut = str_replace("/", "_", $sOut);
    $sOut = str_replace("=", ".", $sOut);
    return $sOut;
}

/**
 *  * 用於字串的 URL 參數方式傳遞的編碼 decode
 *   */
function BinXorDecode($sInput) {
    global $sXorKey, $sPrivateKey;
    $sInput = str_replace(",", "+", $sInput);
    $sInput = str_replace("_", "/", $sInput);
    $sInput = str_replace(".", "=", $sInput);
    $sInput = base64_decode($sInput);
    $sHash = bin2hex(substr($sInput, 0, 16));
    $sInput = substr($sInput, 16);
    if ($sHash != md5($sInput.$sPrivateKey)) { return false; }
    $sOut = $sInput ^ str_repeat($sXorKey, ceil(strlen($sInput)/strlen($sXorKey)));
    return $sOut;
}

$string = "我要加密怎麼著吧有什麼不服的我就不服你了";
$encode = BinXorEncode($string);
$decode = BinXorDecode($encode);

echo "String:|".$string."| ";

echo "Encode:|".$encode."| ";

echo "Decode:|".$decode."| ";

?>

輸出:

String:|我要加密
怎麼著吧
有什麼不服的
我就不服你了|
Encode:|ZP,dd3V5X0nAf,WH9a59Fq25s9_d5PKAdvKr55H2hYnvKZP284Dwg4iAjdyXn1H449,,1t3EmKDWqq8.|
Decode:|我要加密
怎麼著吧
有什麼不服的
我就不服你了| 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.