簡體   English   中英

使用 Python 3 解碼消息

[英]Decode a message using Python 3

我正在嘗試解碼一條用 Java 編碼的消息。 以下是我們的 Java 開發人員的代碼片段:

$encrypted = base64_decode(urldecode($value));
  $decrypted = "";
  openssl_private_decrypt($encrypted, $decrypted, $key);

我正在嘗試使用帶有私鑰的 Python 解碼字符串:

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import base64
from urllib.parse import unquote

private_key="Private_key"
cipher = PKCS1_OAEP.new(private_key)
mesg='some mesg'
# For URL encoder
a=unquote(mesg)
encrypted=base64.b64decode(a.encode("utf-8"))
# before decrypt convert the hex string to byte_array 
message = cipher.decrypt(bytearray.fromhex(encrypted))
print(message)

我在下面收到錯誤,我正在使用 Python 3

TypeError: fromhex() argument must be str, not bytes

在 Python 2.7 上使用 pyCrypto,這就是解密 RSA 公鑰加密的方法。 在 python 3 中它可能略有不同,但我很確定它應該接近或相同。

 from Crypto.Cipher import PKCS1_OAEP
 from Crypto.PublicKey import RSA  

 key = RSA.importKey('PrivateKeyString', passphrase=None)

 def decrypt(self, message):
    return PKCS1_OAEP.new(key).decrypt(message)

 print(decrypt('EncryptedMessage'))

有關這方面的更多信息,您應該閱讀文檔

對於比我更書呆子的人,這里有一些關於這個例子中使用的類/對象的更多信息。

以下三個注釋腳本可以啟發如何將Asymmetric Cryptography with Python文章應用於您的問題(在 Windows 10、Python 3.5 中工作):

  • 45360327_keys.py subsidiary ,只運行一次,沒有輸出到std out:
    • 創建一個私鑰/公鑰對並將它們保存到pem文件中以供其他腳本進一步使用;
  • 45360327_encrypt.py subsidiary ,創建加密值:
    • 從管道或行參數中獲取要加密的消息。 如果未提供,則使用示例字符串(捷克語 pangram),
    • 使用讀取的公鑰對其進行加密,並且
    • 打印已轉換為安全傳輸所需格式的加密消息(url 轉義的 base64 字符串);
  • 45360327.py主要回答模仿給定的 (PHP) 代碼片段
    • 從管道或行參數(強制)中獲取要解密的值,並打印解密的字符串(使用先前保存的私鑰解密)。

示例用法(默認字符串)

.\SO\45360327_keys.py
.\SO\45360327_encrypt.py|.\SO\45360327.py
 Příliš žluťoučký kůň úpěl ďábelské ódy

示例用法(提供了一個俄語 pangram 來加密/解密, pem文件已經創建。重要!在 Windows 中: chcp 65001

>NUL chcp 65001
echo Друг мой эльф! Яшке б свёз птиц южных чащ!|.\SO\45360327_encrypt.py|.\SO\45360327.py
 Друг мой эльф! Яшке б свёз птиц южных чащ!

45360327.py (這個腳本包含我的答案):

# -*- coding: utf-8 -*

# the script mimics the following (PHP) code snippet: 
'''
  $encrypted = base64_decode(urldecode($value));
  $decrypted = "";
  openssl_private_decrypt($encrypted, $decrypted, $key);
'''

# take value from pipeline or from the first line argument
import sys
if not sys.stdin.isatty():
    for arg in sys.stdin:
        value = arg.replace('\n', '').replace('\r','')
else:
    if len(sys.argv) == 2:
        value = sys.argv[1]
    else:
        value=''

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import base64
from urllib.parse import unquote

encrypted_message = base64.b64decode( unquote( value))

# import private key from file, converting it into the RsaKey object   
pr_key = RSA.import_key(open('privat_45360327.pem', 'r').read())

# instantiate PKCS1_OAEP object with the private key for decryption
decrypt = PKCS1_OAEP.new(key=pr_key)
# decrypt the message with the PKCS1_OAEP object
decrypted_message = decrypt.decrypt(encrypted_message)

print(decrypted_message.decode('utf8'))

45360327_encrypt.py (子腳本):

# -*- coding: utf-8 -*
# take the message to be encrypted from pipeline or from line argument
import sys
if not sys.stdin.isatty():
    for arg in sys.stdin:
        rawmessage = arg.replace('\n', '').replace('\r','')
else:
    if len(sys.argv) == 2:
        rawmessage = sys.argv[1]
    else:
        rawmessage='Příliš žluťoučký kůň úpěl ďábelské ódy'
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from binascii import hexlify
import base64
from urllib.parse import quote, unquote
# import public key from file, converting it into the RsaKey object   
pu_key = RSA.import_key(open('public_45360327.pem', 'r').read())
# instantiate PKCS1_OAEP object with the public key for encryption
cipher = PKCS1_OAEP.new(key=pu_key)
# prepare the message for encrypting 
message=unquote(rawmessage).encode("utf-8") 
# encrypt the message with the PKCS1_OAEP object
encrypted_message = cipher.encrypt(message)
# send the encrypted message to std output (print function does that)
print(quote(base64.b64encode(encrypted_message)))

45360327_keys.py (子腳本,運行一次):

# -*- coding: utf-8 -*

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

# generate private key (RsaKey object) of key length of 1024 bits
private_key = RSA.generate(1024)
# generate public key (RsaKey object) from the private key
public_key = private_key.publickey()

# convert the RsaKey objects to strings 
private_pem = private_key.export_key().decode()
public_pem = public_key.export_key().decode()

# write down the private and public keys to 'pem' files
with open('privat_45360327.pem', 'w') as pr:
    pr.write(private_pem)
with open('public_45360327.pem', 'w') as pu:
    pu.write(public_pem)

暫無
暫無

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

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