Reputation: 233
I have been translating PHP code to Python because my company is switching language and framework, but i am stuck on this one method, i can't seems to find the Python equivalent for it.
This is the PHP code:
function addpadding($string, $blocksize = 32) {
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
function create_mpg_aes_encrypt($parameter = '', $key = '', $iv = '') {
$return_str = http_build_query($parameter);
return trim(bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($return_str), MCRYPT_MODE_CBC, $iv)));
}
This is my python code:
def addpadding_pay2go(string, blocksize=32):
length = len(string)
pad = blocksize - (length % blocksize)
padding_strings = chr(pad) * pad
new_string = string + padding_strings
return new_string
Now for the create_mpg_aes_encrypt, i can only re-create the first line in Python, i don't know how to do the second line.
test_array = {
'MerchantID' : 'XXX',
'RespondType' : 'JSON',
'TimeStamp' : unixtime,
'Version' : '1.4',
'MerchantOrderNo' : 1,
'Amt' : 10,
'ItemDesc' : 'product description',
'Key' : 'XXXXX',
'IV' : 'XXXXX'
}
return_str = urllib.urlencode(test_array)
I can do the trim and bin2hex. But my only problem is "how to re-create this in Python?"
mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($return_str), MCRYPT_MODE_CBC, $iv)
Upvotes: 0
Views: 1236
Reputation: 233
I tried this, i don't know whether it is correct or not
from Crypto.Cipher import AES
import urllib
def addpadding_pay2go(string, blocksize=32):
length = len(string)
pad = blocksize - (length % blocksize)
padding_strings = chr(pad) * pad
new_string = string + padding_strings
return new_string
def create_mpg_aes_encrypt(test_array, key, iv):
return_str = urllib.urlencode(test_array)
return_str_with_padding = addpadding_pay2go(return_str)
AES.key_size = 128
crypt_object = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
encrypted_text = crypt_object.encrypt(return_str_with_padding)
hex = encrypted_text.encode('hex')
hex_with_strip = hex.strip()
return hex_with_strip
Upvotes: 1