PHP equivalent of .net AES encryption

前端 未结 2 1704
不思量自难忘°
不思量自难忘° 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:51

    It seems like the PHP Script is Using the wrong Mode:
    https://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.mode%28v=vs.110%29.aspx
    The C# Functions do not set any Mode so the default is CBC.
    The PHP part uses ECB instead, which is not only wrong, but insecure.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题