当您从 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