1

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)
3
  • It is best not to use mcrypt, it is abandonware, has not been updated in years and does not support standard PKCS#7 (née PKCS#5) padding, only non-standard null padding that can't even be used with binary data. mcrypt has many outstanding bugs dating back to 2003. The mcrypt-extension is deprecated will be removed in PHP 7.2. Instead consider using defuse or RNCryptor, they provide a complete solution and are being maintained and is correct. Commented Jul 14, 2017 at 1:45
  • Well… of course that doesn't work. Your Python code is using a completely different cipher! Commented Jul 14, 2017 at 1:50
  • And different modes and different padding. Commented Jul 14, 2017 at 2:00

1 Answer 1

2
  • 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.