简体   繁体   中英

Decode a message using Python 3

I am trying to decode a message which is encoded in Java. Below is the snippet of code from our Java developer:

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

I am trying decode the string using Python with private key:

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)

I am getting an error below, and I am using Python 3

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

Using pyCrypto on Python 2.7, This is how you can decrypt RSA Public Key encryption. In python 3 it may be slightly different, but I'm pretty sure it should be close or the same.

 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'))

For more information on this, you should read the Documentation .

For nerdier people than me, here's a little more on the Class/Object used for this example .

The following three commented scripts could enlighten how to apply Asymmetric Cryptography with Python article to your problem (work in Windows 10, Python 3.5):

  • 45360327_keys.py subsidiary , run only once, no output to std out:
    • creates a private/public key pair and saves them to pem files for further use in other scripts;
  • 45360327_encrypt.py subsidiary , creates an encrypted value:
    • takes a message to be encrypted from pipeline or from line argument. Uses a sample string (Czech pangram) if not supplied,
    • encrypts it using read public key, and
    • prints encrypted message converted to format required for safe transport (url-escaped base64 string);
  • 45360327.py primary answering , mimics the given (PHP) code snippet :
    • takes a value to be decrypted from pipeline or from line argument (mandatory), and prints decrypted string (decrypts using previously saved private key).

Sample usage (default string)

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

Sample usage (supplied a Russian pangram to encrypt/decrypt, pem files already created. Important! in Windows: chcp 65001 :

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

45360327.py (this script contains my answer):

# -*- 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 (subsidiary script):

# -*- 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 (subsidiary script, run once ):

# -*- 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM