Let's say I have a Phonegap / cordova app and I want to make requests to my server with POSTs and GETs throught AJAX.
How can I secure my php file to do only if the post come from my app. E.G.
if($_POST["key"]==$secret_key_got_from_server) {
// Do the things
}
I wanted to create a secure unique key with openssl, but if I hardcode it in the code to send it throught AJAX, anyone could just decompile my source code and get the key and do whatever he wants.
How could I make sure my post come from my phonegap app, or how can I securily code that key/token ?
I'm not quite sure if this question should be here or in security SE.
How could I make sure my post come from my phonegap app, or how can I securily code that key/token ?
You can't. Full stop. Reverse engineering exists in the world, and that genie has been out of the bottle for at least 40 years.
Ask yourself, "Why is it necessary to ensure that the data can only come from my app?" You're very likely trying to solve the wrong problem.
To check whether the origin of the given POST message is legitimate user or not, you should consider the authentication of the message. There can be various ways to achieve the authentication, but common way is to use token that is issued when sign up or login process. If the post message contains valid token, we can regard that the message is sent from valid user and otherwise is not a valid request. Recently JWT is widely used for web application. These sites may be helpful: JWT.io, JWT - Wikipedia
In this case, if attackers can capture and modify your POST message, then the your scheme fails. To prevent this attack scenario, you need to encrypt your message. As you say, if you hardcode the secret key on the client side app, attackers can know the key by analyzing the client side app. So the better way is to encrypt the message by using the public key of the server. Public key is only for the encryption and it is computationally impossible to decrypt message using the public key. Decryption is done by private key which should be securely stored in the server.
These public key and private key based encryption methods are called public key cryptosystem (PKC). For instance, RSA and ECC are most well-known public key crypyosystem.
For the web application, HTTPS protocol is provided. You can encrypt your POST message using HTTPS.
Note that Encryption itself doesn't provide integrity and authentication. Encryption just hide the message, but not guarantee that the message is sent from the valid user.