繁体   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