我正在尝试获取此代码,并使其打印回我给的代码。
from subprocess import Popen
from selenium import webdriver
from bs4 import BeautifulSoup
import string
import time
import random
import csv
import pandas as pd
from pick import pick
import requests
import re
import urllib.request
from urllib.request import urlopen
from selenium.webdriver.common.by import By
from tkinter import *
import tkinter as tk
import tkinter.filedialog as filedialog
import os
import pyodbc
from decimal import *
import sys
from PySide2 import QtCore, QtGui, QtWidgets
from datetime import datetime, date
from decimal import Decimal
我可以通过调用对密钥进行异或
def xorwithmykey(str,key):
kp = 0
newbuf = []
for i in range(len(str)):
newchar = ord(str[i]) ^ ord(key[kp])
newbuf.append(chr(newchar))
kp = kp + 1
if kp >= len(key):
kp = 0
return ''.join(newbuf).encode('hex')
这给了我
encoded = xorwithmykey('encodethis', 'akey')
现在我想把它还给相同的函数进行解码。
b'04050616050e11110818'
这将返回错误:
decoded = xorwithmykey(codecs.decode(encoded, 'hex'), codecs.decode('akey', 'hex')
我在这里找到了这个示例:https://snippets.bentasker.co.uk/page-1708032328-XOR-string-against-a-given-key-Python.html
但是它在Python 2中,我正在尝试转换为Python 3。
答案 0 :(得分:0)
如果您限制XOR函数只能在Python 3中使用字节,则可以对任何Unicode字符串进行编码/解码:
from binascii import hexlify
# Shorter version
# def xorwithmykey(s,key):
# return bytes([c ^ key[i%len(key)] for i,c in enumerate(s)])
def xorwithmykey(s,key):
kp = 0
newbuf = []
for i in range(len(s)):
newchar = s[i] ^ key[kp]
newbuf.append(newchar)
kp = kp + 1
if kp >= len(key):
kp = 0
return bytes(newbuf)
encoded = xorwithmykey('She said, "你好!"'.encode(), b'akey')
print(hexlify(encoded))
decoded = xorwithmykey(encoded, b'akey')
print(decoded.decode())
输出:
b'32030059120a0c1d4d4b479ddccb80dcdc84d9f843'
She said, "你好!"