使用Python 3解码消息

时间:2017-07-27 20:20:03

标签: python python-3.x cryptography decode encode

我正在尝试解码用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

2 个答案:

答案 0 :(得分:0)

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

有关此内容的更多信息,请阅读Documentation

对于比我更神经质的人,这里有更多关于用于this example的类/对象的内容。

答案 1 :(得分:0)

以下三个 commented 脚本可以启发如何将Asymmetric Cryptography with Python文章应用于您的问题(在Windows 10,Python 3.5中有效):

  • 45360327_keys.py    子公司,仅运行一次,没有输出要输出:
    • 创建一个私钥/公钥对,并将它们保存到pem文件中,以便在其他脚本中进一步使用;
  • 45360327_encrypt.py 子公司,创建一个加密值:
    • 从管道或行参数获取要加密的消息。如果未提供,则使用示例字符串(捷克字母),
    • 使用读取的公共密钥对其进行加密,并且
    • 打印加密的消息,将其转换为安全传输所需的格式(转义的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:< / p>

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