Search code examples
pythonpycrypto

How to extract the binary string from the string


I have a tricky question of how to process a string. I need to process a payload from the link, the payload is a encrypted binary string looks like this:

payload=b'F4ChGNL/Pemxy8l6cCR......'

AS you can see, it is a bytes. However, when I try to fetch the payload through AWS gateway and Lambda function something like: payload=event['queryStringParameters']['payload'] The payload variable is actually a type of string. which makes the decrypt failed.

def lambda_handler(event, context):     
    #Decode from base64
    str_64_enc=event['queryStringParameters']['payload']
    str_enc=base64.b64decode(str_64_enc)
    print(str_enc)
    
    #Decrypt by private key
    pr_key = RSA.importKey(open('private_pem.pem', 'r').read())
    decrypt = PKCS1_OAEP.new(key=pr_key)
    decrypted_message = decrypt.decrypt(str_enc)
    print(decrypted_message)

Please advise what is the right way to process this case. Thanks


Solution

  • You did correctly for decoding a base64 encoded string or bytes. It's not the problem of converting a string to bytes and vice versa. Since the base64 encoding only uses ASCII characters, base64.decode() automatically converts a string to bytes, like the following example.

    import base64
    
    src_bytes = b'\x00\x01\x02\x03'
    b64_bytes = base64.b64encode(src_bytes)
    b64_str = b64_bytes.decode('ascii')
    assert(b64_str.encode('ascii') == b64_bytes)
    assert(base64.b64decode(b64_str) == src_bytes)
    assert(base64.b64decode(b64_bytes) == src_bytes)
    

    You should check the bytes decoded from the payload parameter is really the result of encrypting a bytes with RSA-OAEP algorithm.