python - Rc4 解密 ValueError:“str”类型的对象的未知格式代码“x”
问题描述
当我到达代码中的以下行时,我收到以下错误:
inputString = "{:02x}".format(inputNumber)
ValueError:“str”类型的对象的未知格式代码“x”
我怎样才能避免这种情况?
# Global variables
state = [None] * 256
p = q = None
def setKey(key):
##RC4 Key Scheduling Algorithm
global p, q, state
state = [n for n in range(256)]
p = q = j = 0
for i in range(256):
if len(key) > 0:
j = (j + state[i] + key[i % len(key)]) % 256
else:
j = (j + state[i]) % 256
state[i], state[j] = state[j], state[i]
def byteGenerator():
##RC4 Pseudo-Random Generation Algorithm
global p, q, state
p = (p + 1) % 256
q = (q + state[p]) % 256
state[p], state[q] = state[q], state[p]
return state[(state[p] + state[q]) % 256]
def encrypt(key,inputString):
##Encrypt input string returning a byte list
setKey(string_to_list(key))
return [ord(p) ^ byteGenerator() for p in inputString]
def decrypt(inputByteList):
##Decrypt input byte list returning a string
return "".join([chr(c ^ byteGenerator()) for c in inputByteList])
def intToList(inputNumber):
##Convert a number into a byte list
inputString = "{:02x}".format(inputNumber)
return [(inputString[i:i + 2], 16) for i in range(0, len(inputString), 2)]
def string_to_list(inputString):
##Convert a string into a byte list
return [ord(c) for c in inputString]
loop = 1
while loop == 1: #simple loop to always bring the user back to the menu
print("RC4 Encryptor/Decryptor")
print
print("Please choose an option from the below menu")
print
print("1) Encrypt")
print("2) Decrypt")
print
choice = input("Choose your option: ")
choice = int(choice)
if choice == 1:
key = input("Enter Key: ")
inputstring = input("enter plaintext: ")
print(encrypt(key, inputstring))
elif choice == 2:
key = input("Enter Key: ")
ciphertext = input("enter plaintext: ")
print(decrypt(intToList(ciphertext)))
elif choice == 3:
#returns the user to the previous menu by ending the loop and clearing the screen.
loop = 0
else:
print ("please enter a valid option") #if any NUMBER other than 1, 2 or 3 is entered.
解决方案
看起来您正在尝试将字符串转换为十六进制。不幸的是,这不是这样做的方法:"{:02x}".format
用于格式化单个整数,因此它不适用于整个字符串。
Python 3 包含bytes.hex()
为您执行此转换的方法,但您需要一个字节字符串而不是普通字符串。您可以使用字符串编码将 str 转换为字节。
如果您想自己进行转换,您可以调用"{:02x}".format
字符串中每个字符的字符代码,并将各个十六进制值连接在一起。在这种情况下要小心使用 Unicode;使用字节字符串可能会更好。
推荐阅读
- ios - RealmSwift 降级迁移
- performance - Entity Framework 3.1 中的跟踪开销是多少?
- go - 解析 jwt 令牌时在哪里验证 JWT 密钥?
- nosql - 如何访问 DynamoDB 中的关系数据(键与查询)
- sql - TERADATA, CASE IN WHERE CLAUSE
- c# - 提供程序“Microsoft.Jet.OLEDB.4.0”未在本地计算机上注册
- reactjs - react-hook-form Controller onBlur 回调未触发验证
- matplotlib - 在 matplotlib 中缩放球面投影
- arrays - 通过 onClick 从数组中删除元素(useState)
- python - np.sort(X,axis=1) 不对数组进行排序?