douyangqian5243 2019-02-27 02:13
浏览 94

如何在python中编码字符串并在php服务器上解码它

I have a python app that communicates with a php server. I am trying to pass an encrypted string from the python app to the php server to be decoded and stored:

Python Code

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)

encode function:

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 code

$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();

decode function

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;

I have tested the encode/decode function pairing separately and they function properly, but once i try to pass the encoded string with the http request (using python requests) things go haywire and it doesn't decode the string properly. How can i pass this encrypted string to my php server and then decode it?

Note

I am aware this isn't at all secure. That is not of importance as the information isn't sensitive. As a programming exercise I am trying to add a simple layer of obfuscation to the information being passed. I am just trying to figure out why the encrypted string is not being decrypted properly on the server side.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 关于大棚监测的pcb板设计
    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题
    • ¥20 win11修改中文用户名路径
    • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入