2

我正在使用 Python 开发一个服务器应用程序,以及一个用 Java 连接到它的应用程序。我需要在 Java 中加密字符串,然后在 Python 中解密。

Java 代码一切正常,但 Python 代码存在问题。

from Crypto.Cipher import AES
obj        = AES.new('0123456789abcdef', AES.MODE_CBC,IV="fedcba9876543210")
BLOCK_SIZE = 16
PADDING    = " "
pad        = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
plain      = "password"
plain      = pad (plain)
ciph       = obj.encrypt(plain)
obj        = AES.new('0123456789abcdef', AES.MODE_CBC,IV="fedcba9876543210")
decrypted  = obj.decrypt(ciph)
result     = ""
for char in ciph:
    result += str((hex(ord(char))))[2:]
print result
print decrypted

结果是:

2af41fc02b33765b56433f59edb67dd3
password

这是我所期望的并与 Java 输出匹配,但是当我插入两行中的第一行以在 Python 代码中对其进行解密时,输出完全关闭并显示随机字符。我认为这是由于最后的 for 循环使其与 Java 输出相同。有没有办法撤消那个for循环?同样使用至少与此类似的代码是否有一种不错的方法来解密两个输出字符串中的第一个字符串(在 Python 中)?

感谢所有回复,提前感谢您!

4

1 回答 1

1

中的每一对数字result都是十六进制字符的字符代码。这是一个重现转换并撤消它的片段(有更优雅的方法可以做到这一点,但它很简单并且有效)。

import re

ciph = "hello there"
result = ""
for c in ciph:
    result += str((hex(ord(c))))[2:]

# reverse it
orig = ""
for code in re.findall('..', result):
    orig += chr(int(code, 16))
print orig  # "hello there"
于 2012-11-04T23:12:37.340 回答