|
| 1 | +import base64 |
| 2 | +from Crypto.Hash import SHA256 |
| 3 | +from Crypto.PublicKey import RSA |
| 4 | +from Crypto.Signature import PKCS1_v1_5 |
| 5 | +from time import strftime |
| 6 | + |
| 7 | +__all__ = ["OpenAuth", "SecretAuth", "RsaSha256Auth"] |
| 8 | + |
| 9 | + |
| 10 | +class OpenAuth(object): |
| 11 | + """Attaches no authentication to the given Request object.""" |
| 12 | + |
| 13 | + def __call__(self, method, url, headers, body): |
| 14 | + return method, url, headers, body |
| 15 | + |
| 16 | + |
| 17 | +class SecretAuth(object): |
| 18 | + """Attaches Authentication with secret token to |
| 19 | + the given Request object.""" |
| 20 | + |
| 21 | + def __init__(self, secret): |
| 22 | + self.secret = secret |
| 23 | + |
| 24 | + def __call__(self, method, url, headers, body): |
| 25 | + headers['Authorization'] = 'SECRET ' + self.secret |
| 26 | + return method, url, headers, body |
| 27 | + |
| 28 | + |
| 29 | +class RsaSha256Auth(object): |
| 30 | + """Attaches RSA authentication to the given Request object.""" |
| 31 | + |
| 32 | + def __init__(self, privkey): |
| 33 | + self.signer = PKCS1_v1_5.new(RSA.importKey(privkey)) |
| 34 | + |
| 35 | + def __call__(self, method, url, headers, body): |
| 36 | + headers['X-Mcash-Timestamp'] = self._get_timestamp() |
| 37 | + headers['X-Mcash-Content-Digest'] = self._get_sha256_digest(body) |
| 38 | + headers['Authorization'] = self._sha256_sign(method, url, headers, body) |
| 39 | + return method, url, headers, body |
| 40 | + |
| 41 | + def _get_timestamp(self): |
| 42 | + """Return the timestamp formatted to comply with |
| 43 | + Merchant API expectations. |
| 44 | + """ |
| 45 | + return str(strftime("%Y-%m-%d %H:%M:%S")) |
| 46 | + |
| 47 | + def _get_sha256_digest(self, content): |
| 48 | + """Return the sha256 digest of the content in the |
| 49 | + header format the Merchant API expects. |
| 50 | + """ |
| 51 | + content_sha256 = base64.b64encode(SHA256.new(content).digest()) |
| 52 | + return 'SHA256=' + content_sha256 |
| 53 | + |
| 54 | + def _sha256_sign(self, method, url, headers, body): |
| 55 | + """Sign the request with SHA256. |
| 56 | + """ |
| 57 | + d = '' |
| 58 | + sign_headers = method.upper() + '|' + url + '|' |
| 59 | + for key, value in sorted(headers.items()): |
| 60 | + if key.startswith('X-Mcash-'): |
| 61 | + sign_headers += d + key.upper() + '=' + value |
| 62 | + d = '&' |
| 63 | + |
| 64 | + rsa_signature = base64.b64encode( |
| 65 | + self.signer.sign(SHA256.new(sign_headers))) |
| 66 | + |
| 67 | + return 'RSA-SHA256 ' + rsa_signature |
0 commit comments