2017-05-06 94 views
0

我對python程序設計相當陌生,但我正在嘗試爲學校項目製作我自己的簡單加密程序。經過大量研究後,我終於開始了,主要是關於不同python命令的語法。無論如何,我的代碼的一部分涉及將兩行文本(密鑰和msg)翻譯成十六進制,以執行我簡單的加密算法。儘管一切看起來都正確,但我有時會在十六進制字符串的末尾得到大寫字母L的輸出。 (下面的代碼示例)任何建議都會有幫助!用python編寫十六進制程序的文字問題

假設味精= 「Hello World」 的和關鍵=「例如/ ABC。

# define functions 

def function_hex(string, length): 
    variable = "0x00" 
    for i in xrange(0, length): 
    n = ord(string[i]) 
    variable = hex(256 * int(variable, 16) + n)  #line 24 
    return variable 

# transform input/key to hex 

msg_hex = function_hex(msg, msg_length)    #line 29 
print msg_hex 

key_hex = function_hex(key, key_length) 
print key_hex 

輸出

message: hello world 
key: /abc 
encrypt or decrypt: encrypt 
Traceback (most recent call last): 
    File "python", line 29, in <module> 
    File "python", line 24, in function_hex 
ValueError: invalid literal for int() with base 16: '0x68656c6c6f20776f72L' 

回答

0

山姆, 我可以提出一個更好的方法?

# define functions 
msg = "hello world" 
key = "/abc" 

def function_hex(s): 
    return "0x" + "".join("{:02x}".format(ord(c)) for c in s) 

# transform input/key to hex 

msg_hex = function_hex(msg) 
print msg_hex 

key_hex = function_hex(key) 
print key_hex