I'm trying to encrypt string using the key send from an application by using POST Method.The POST Method sends the key for encryption.But the script is not working correctly please help me out.
1 Answer
The reason it doesn't work is your padding is wrong. PKCS7 is the byte value of the pad length repeated(i.e. 00000010 00000010 if your padding 2 bytes). It is not the string value "0202", It appears there aren't any php functions that do this correctly, so I'd sugest you use a a mode of operation that does not need padding. OFB is supported by both c# and php.
YOU CANNOT USE A Fixed IV. For cbc mode, its fairly insecure, for OFB, its completely insecure. Use mcrypt_create_iv to get a new random one each time. Then just prepend the IV to the ciphertext when you send it ( it does not need to be encrypted). As a note, one problem you may already have hit is that php uses a string and C# uses byts for the IV and you may not be getting the correct conversion even now . I'd probably use hex and the functions to covert to/from that just to be sure.
Second, you need to use something to detect when people tamper with your data, otherwise they potentially read the cipher text via error codes/ timing issues in the underlying crypto libraries. Hmacs work well and are supported here for php and here for c#. HMAC your IV+ciphertext message and prepend the output to it . On the other end, run the c# equivalent function over the same data, and then compare the HMAC values. If they are the same,you safe, if not, reject.