【问题标题】:Decode a message using Python 3使用 Python 3 解码消息
【发布时间】:2018-01-03 17:54:36
【问题描述】:

我正在尝试解码以 Java 编码的消息。以下是我们 Java 开发人员的 sn-p 代码:

$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

【问题讨论】:

  • 我不知道,但您只是将您的私钥粘贴到 stackoverflow 上吗?
  • 是什么让你认为那是 Java?
  • 请确保使该私钥无效并用新密钥替换。
  • 使私钥失效很重要。我标记了该帖子,但如果您查看编辑历史记录,它仍然可见。
  • Poke 肯定会的.. 这是一个错误

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


【解决方案1】:

在 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 的类/对象。

【讨论】:

    【解决方案2】:

    以下三个评论脚本可以启发如何将Asymmetric Cryptography with Python 文章应用于您的问题(在 Windows 10、Python 3.5 中工作):

    • 45360327_keys.py   subsidiary,只运行一次,没有输出到标准输出:
      • 创建一个私钥/公钥对并将它们保存到pem 文件中以供其他脚本进一步使用;
    • 45360327_encrypt.py subsidiary,创建一个加密值:
      • 从管道或线路参数中获取要加密的消息。如果未提供,则使用示例字符串(捷克语 pangram),
      • 使用读取的公钥对其进行加密,然后
      • 打印转换为安全传输所需格式的加密消息(url 转义的 base64 字符串);
    • 45360327.py         主要回答模仿给定的 (PHP) 代码 sn-p
      • 从管道或线路参数中获取要解密的值(强制),并打印解密后的字符串(使用之前保存的私钥解密)。

    示例用法(默认字符串)

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

    【讨论】:

    • 我正在尝试解码一个大字符串,总是得到 ValueError("Ciphertext with wrong length."),php 代码使用 $chunkSize = ceil(1024 / 8); $chunk = substr($encryptString, 0, $chunkSize);如何在 python 3 中做同样的事情?编码字符串[:math.ceil(1024/8)] 不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多