簡體   English   中英

Rc4 decrypt ValueError:object 類型為“str”的未知格式代碼“x”

[英]Rc4 decrypt ValueError: Unknown format code 'x' for object of type 'str'

當我到達我的代碼中的以下行時,我收到以下錯誤:

inputString = "{:02x}".format(inputNumber)

ValueError:類型為“str”的 object 的未知格式代碼“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.

格式字符串代碼x將 integer 轉換為其十六進制表示形式的字符串。 例如:

>>> "{:02x}".format(54563)
'd523'

當您將字符串作為inputNumber傳遞時,會出現您遇到的錯誤。 Arguments 傳遞給您的intToList function 應該是整數。 考慮使用intToList(int(your_argument_here))

看起來您正在嘗試將字符串轉換為十六進制。 不幸的是,這不是這樣做的方法: "{:02x}".format用於格式化單個 integer,因此它不適用於整個字符串。

Python 3 包括方法bytes.hex()為您執行此轉換,但您需要字節字符串而不是普通字符串。 您可以使用字符串編碼將 str 轉換為 bytes。

如果您想自己進行轉換,可以對字符串中每個字符的字符代碼調用"{:02x}".format ,並將各個十六進制值連接在一起。 在這種情況下要小心 Unicode; 使用字節字符串可能會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM