How to decode base64 url in python?

前端 未结 9 1372
一个人的身影
一个人的身影 2020-12-28 15:24

For Facebook fbml Apps Facebook is sending in a signed_request parameter explained here:

http://developers.facebook.com/docs/authentication/canvas

They have

相关标签:
9条回答
  • 2020-12-28 15:32

    Apparently you missed the last two characters when copying the original base64-encoded string. Suffix the input string with two is-equal (=) signs and it will be decoded correctly.

    0 讨论(0)
  • 2020-12-28 15:37

    try

    s = 'iEPX-SQWIR3p67lj_0zigSWTKHg'
    base64.urlsafe_b64decode(s + '=' * (4 - len(s) % 4))
    

    as it is written here

    0 讨论(0)
  • 2020-12-28 15:40

    Alternative to @dae.eklen's solution, you can append === to it:

    s = 'iEPX-SQWIR3p67lj_0zigSWTKHg'
    base64.urlsafe_b64decode(s + '===')
    

    This works because Python only complains about missing padding, but not extra padding.

    0 讨论(0)
  • 2020-12-28 15:41

    If you are sending your base64 string from .net as a param it seems that chars that have special meaning in the URI ie + or / are replaced with " " spaces.

    So before you send your string in .net you should probably do something like this

    base64img.Replace("+", "-").Replace("/", "_"))
    

    Then in python decode the string (also add '=' until the length is divisible by 4)

    def decode_base64(data):
        data += '=' * (len(data) % 4)
        return base64.urlsafe_b64decode(data)
    

    Further if you want to use the image in openCV

    def get_cv2_img_from_base64(base_64_string):
        data = decode_base64(base_64_string)
        np_data = np.frombuffer(data, dtype=np.uint8)
        return cv2.imdecode(np_data, cv2.IMREAD_UNCHANGED)
    
    0 讨论(0)
  • 2020-12-28 15:44

    just

    base64.urlsafe_b64decode(s)
    
    0 讨论(0)
  • 2020-12-28 15:50
    import base64
    import simplejson as json
    
    def parse_signed_request( signed_request ):
        encoded_sig, payload = signed_request.split('.',2)
        data = json.loads(base64.b64decode( payload.replace('-_', '+/') ))
        return data
    
    0 讨论(0)
提交回复
热议问题