如何在python中编码字符串并在php上解码

2024-03-28 08:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个与php服务器通信的python应用程序。我正在尝试将一个加密字符串从python应用程序传递到php服务器以进行解码和存储:

Python代码

url = "http://www.steventaylordevelopment.com/php/rk2.php"
entry = {"username": encode("sdjfkhkj2h34", "username"),
         "mode": "hardcore",
         "score": 121114,
         "attempts": 15,
         "time": 12121,
         "rank": "prince"}
d = {"action": "addEntry",
     "entry": json.dumps(entry)}
r = requests.post(url=url, data=d)

编码功能:

def encode(key, string):
    encoded_chars = []
    for i in range(len(string)):
        key_c = key[i % len(key)]
        encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = ''.join(encoded_chars)
    return encoded_string

PHP代码

$entry = json_decode($_POST["entry"], true);
$decoded_username = decode("sdjfkhkj2h34", $entry["username"]);
$new_entry = $rk2_db->prepare("INSERT INTO leaderboard (username, mode, score, attempts, time, rank, date) VALUES (?, ?, ?, ?, ?, ?, NOW())");
$new_entry->bind_param("ssiiis", $decoded_username, $entry["mode"], $entry["score"], $entry["attempts"], $entry["time"], $entry["rank"]);
$new_entry->execute();
$new_entry->close();

解码功能

function decode($key, $string){
    $encoded_chars = array();
    for($i = 0; $i < strlen($string); $i++){
        $key_c = $key[$i % strlen($key)];
        $encoded_c = chr((ord($string[$i]) - ord($key_c) + 256) % 256);
        array_push($encoded_chars, $encoded_c);
    }
    $decoded_string = implode("", $encoded_chars);
    return $decoded_string;

我已经分别测试了encode/decode函数对,它们可以正常工作,但是一旦我尝试用http请求(使用python请求)传递编码的字符串,事情就会失控,无法正确解码字符串。如何将这个加密字符串传递到php服务器,然后对其进行解码?你知道吗

注意

我知道这根本不安全。这并不重要,因为信息并不敏感。作为一个编程练习,我试图给传递的信息添加一个简单的模糊层。我只是想弄明白为什么加密字符串在服务器端没有被正确解密。你知道吗


Tags: key字符串服务器urlnewstringusername解码