PHP equivalent of .net AES encryption

前端 未结 2 1725
不思量自难忘°
不思量自难忘° 2021-01-29 14:07

I am working on a data exchange integration with my client and the data they send me is encrypted using their C# encrypt method (below).

My app is running

2条回答
  •  情深已故
    2021-01-29 14:53

    Can anyone spot the mistake?

    Yes, and the big one isn't really your fault: mcrypt's confusing API strikes again.

    That said, there are actually multiple mistakes here.

    return rtrim( // unnecessary
        base64_encode(
            mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256, // Not AES
                $secretKey, $plainText,
                MCRYPT_MODE_ECB, // BAD, use MCRYPT_MODE_CBC or 'ctr' instead
                mcrypt_create_iv(
                    mcrypt_get_iv_size(      // unless you're going make this
                        MCRYPT_RIJNDAEL_256, // configurable, you should just
                        MCRYPT_MODE_ECB      // hard-code this as an integer
                    ),
                    MCRYPT_RAND) // BAD, use MCRYPT_DEV_URANDOM
            )
        ), "\0"
    ); 
    

    If you're going to generate an IV, it should be communicated so your recipient can decrypt the same first block successfully. The C# code does this, the PHP does not.

    From a cryptography engineering perspective, you should consider, both in C# land and in PHP, deploying an Encrypt then Authenticate protocol. See this blog post on encryption and authentication. Also, all the crypto code you've ever written is probably broken.

提交回复
热议问题