2017-05-06 54 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