Snippets

EasyPaymentGateway EPG encryption sample

Created by Pete Boucher last modified
# Run this script from the command line using
# $ python epg_sample.py

from Crypto.Cipher import AES
import base64
from hashlib import sha256
import urllib, urllib2

# merchant and secret_key
merchant_id = '2150'
secret = 'pasteYourMd5SecretKey'

epg_endpoint = 'https://checkout-stg.easypaymentgateway.com/EPGCheckout/rest/online/pay'

def encrypt(plaintext, key):
  # the block size for the cipher object; must be 16, 24, or 32 for AES
  BLOCK_SIZE = 16
  # one-liner to sufficiently pad the text to be encrypted
  pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)

  # one-liner to encrypt a string
  # encrypt with AES, encode with base64
  EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))

  # create a cipher object using the secret key
  cipher = AES.new(key, AES.MODE_ECB)

  encoded = EncodeAES(cipher, plaintext)
  print 'cyphertext:', encoded

  return encoded

def integrity_hash(plaintext):
  hash = sha256(plaintext).hexdigest()
  print 'checksum:', hash
  return hash


params = 'amount=10&currency=USD&country=GB&operationType=debit&merchantId=' + merchant_id
print 'plaintext:', params

# encode a string
encoded = encrypt(params, secret)
# generate the checksum
integrity_check = integrity_hash(params)

payload = {'encrypted':encoded, 'integrityCheck':integrity_check, 'merchantId':merchant_id}

print 'POST:', urllib.urlencode(payload)
print 'to endpoint:', epg_endpoint
request = urllib2.Request(url=epg_endpoint,
  data=urllib.urlencode(payload))

f = urllib2.urlopen(request)
print f.read()

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.