簡體   English   中英

解密用Java加密的Python中的字符串

[英]Decrypt String in Python That Was Encrypted in Java

我正在使用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中)?

我感謝所有答復,提前謝謝您!

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"

暫無
暫無

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

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