Reputation: 83
How do I convert this to Python? What I'm confused is the random vi.
PHP
public function fnEncrypt($sValue, $sSecretKey)
{
$sValue = $this->pkcs5_pad($sValue, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'ecb'));
return rtrim(
base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$sSecretKey, $sValue,
MCRYPT_MODE_ECB,
mcrypt_create_iv(
mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_128,
MCRYPT_MODE_ECB
),
MCRYPT_RAND)
)
), "\0"
);
}
UPDATE:
this works exactly how it should!
Python
secret_key = 'he21jodkio1289ij'
value = 'hello'
BLOCK_SIZE = 16
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
PADDING = '\0'
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
cipher = AES.new(secret_key, AES.MODE_ECB)
Upvotes: 1
Views: 1324
Reputation: 112855
The PHP code is using RIJNDAEL_128 which is AES, the Python code is using DES, they both need to use the same encryption algorithm in order to interoperate.
The PHP code is using ECB mode but Python code is using CBC mode, they both need to use the same mode in order to interoperate.
The PHP code mcrypt (which should not be used) uses non-standard null padding, the Python code is using PKCS#5 padding which is standard, they both need to use the same padding in order to interoperate.
Note1: ECB mode does not use an IV. If an IV is provided for ECB mode it is ignored.
Note 2: Do not use ECB mode, it is not secure, see ECB mode, scroll down to the Penguin. Instead use CBC mode with a random IV, just prefix the encrypted data with the IV for use in decryption, it does not need to be secret.
Upvotes: 2