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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!