首页 > 解决方案 > php文件中android volley POST请求的安全性

问题描述

我有一个处理货币交易的应用程序,因此安全性非常重要。当用户向我的 php 文件发送请求时,我使用密码和其他一些技巧,但我想知道是否有可能让 php 文件验证 POST 方法仅从我的应用程序和 Volley 发送?

我不想接受来自网页或其他任何东西的请求;只有我对 Android Volley 的请求才得以执行。

PS:从 POST 方法发送值并检查 PHP 以识别不是安全方法,并且很容易被黑客入侵。

标签: phpandroidsecurityandroid-volley

解决方案


当您从 android 发送请求时,使用某种加密(可能是 RSA)加密您的有效负载,然后在您的服务器端解密该请求,如果解密成功,您可以确定该请求是真实的并且没有被更改。

在 PHP 中生成私钥文件

$config = array(
   "digest_alg" => "sha512",
   "private_key_bits" => 4096,
   "private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$keys = openssl_pkey_new($config);
$priv = openssl_pkey_get_private($keys);
openssl_pkey_export_to_file($priv, 'private.pem');

使用 OpenSSL 从私钥文件生成公共 .der 文件

openssl rsa -in private.pem -pubout -outform DER -out public.der

在Java(Android端)中导入和使用公钥:

File pubKeyFile = new File("public.der");
DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] keyBytes = new byte[(int) pubKeyFile.length()];

dis.readFully(keyBytes);
dis.close();

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);

在 Android 中编码您的有效负载(根据您的要求获取字节)

Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String payload = "tejashwi kalp taru";
byte[] encryptedBytes = Base64.getEncoder().encode(cipher.doFinal(payload.getBytes()));
String encryptedData = new String(encryptedBytes));
//send encryptedData to server for decryption

在 PHP 中解密你的有效载荷:

$fp = fopen("private.pem", "r");
$privateKey = fread($fp, 8192);
fclose($fp);

$res = openssl_get_privatekey($privateKey);
$cipher = base64_decode($cipher);
openssl_private_decrypt( $cipher, $decrypted, $res, OPENSSL_PKCS1_OAEP_PADDING );

// $decrypted is the result

用于演示的 Git 存储库:https ://github.com/tejashwikalptaru/encrypted-communication


推荐阅读