How can I encrypt with AES in C# so I can decrypt it in PHP?

自闭症网瘾萝莉.ら 提交于 2019-11-28 14:40:42

Generally it only depends on selecting the right options on both sides:

  • Plaintext character format

    how plaintext characters are encoded in the bit string

  • Padding

    how to pad the plaintext to be an exact multiple of the block size

  • Key length

    must be agreed if there is a choice

  • Key derivation

    how to create the bit string to be used for the key

  • Mode

    which mode of encryption to use

  • Storage format

    how we store the ciphertext

Please see here for a lot of information about these things. Especially the padding seems to be the root of most interoperability problems as PHP's mcrypt uses a NULL-padding by default and has no built-in support for any other padding mode, while e.g. .NET doesn't even provide an option to use a NULL-padding (as it may cause issues when encrypting binary data).

I know this was asked a while ago but I thought I'd post my solution for others. I wrote up a quick code example in PHP and C# that lets you encrypt/decrypt both ways. I had a few issues with getting the settings on both sides to work out. A difference in padding would let it decrypt one way but not the other

https://github.com/dchymko/.NET--PHP-encryption

hope that helps some people.

Are you using the same mode with both? I.e. are you using CBC with both (and not ECB). If you don't understand what I just said then drop a comment and I'll explain in detail, as it has fairly major security repercussions.

I had a similar problem a few months ago - I had a project that had to use AES encryption and I had to make sure that the exact same algorithm is used between a C# and A C++ component. I ended up implementing a shared DLL library used by both based on the AES crypto wrapper from this codeplex article:

http://www.codeproject.com/KB/security/WinAESwithHMAC.aspx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!