2010年11月20日 星期六

PHP 的 XOR

唉!真不知道該說PHP不用指定變數型態這件事情到底好還是不好! 這兩天在寫一段加密的程式,有用到XOR 結果JAVA和PHP的流程部份一模一樣 結果加密後的結果確有些不相同 更扯的是XOR沒辦法自己解密成功 = = 到最後才發現XOR的字元必須用ord做轉換再做XOR 還好在網上有找到別人寫好的程式碼 ```php /** * XOR encrypts a given string with a given key phrase. * * @param string $InputString Input string * @param string $KeyPhrase Key phrase * @return string Encrypted string */ function XOREncryption($InputString, $KeyPhrase){ $KeyPhraseLength = strlen($KeyPhrase); // Loop trough input string for ($i = 0; $i < strlen($InputString); $i++){ // Get key phrase character position $rPos = $i % $KeyPhraseLength; // Magic happens here: $r = ord($InputString[$i]) ^ ord($KeyPhrase[$rPos]); // Replace characters $InputString[$i] = chr($r); } return $InputString; } // Helper functions, using base64 to // create readable encrypted texts: function XOREncrypt($InputString, $KeyPhrase){ $InputString = XOREncryption($InputString, $KeyPhrase); $InputString = base64_encode($InputString); return $InputString; } function XORDecrypt($InputString, $KeyPhrase){ $InputString = base64_decode($InputString); $InputString = XOREncryption($InputString, $KeyPhrase); return $InputString; } ```