For Facebook fbml Apps Facebook is sending in a signed_request parameter explained here:
http://developers.facebook.com/docs/authentication/canvas
They have
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.
try
s = 'iEPX-SQWIR3p67lj_0zigSWTKHg'
base64.urlsafe_b64decode(s + '=' * (4 - len(s) % 4))
as it is written here
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.
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)
just
base64.urlsafe_b64decode(s)
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