You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含敏感数据的Android应用:免费实现安全传输至PHP及MySQL加密存储问询

Hey there! This is a solid school project question—let's walk through free, practical steps to get secure data transmission and encrypted storage working for your Android + PHP + free MySQL setup. All of these tools and methods are totally free and fit perfectly for a school assignment.

Secure Data Transmission (Free & Easy to Implement)

1. Enable HTTPS for Your PHP Page

Most free PHP hosts (like InfinityFree or 000webhost) offer free Let's Encrypt SSL certificates. Just head to your host's control panel, find the SSL section, and follow the prompts to activate it. This ensures every bit of data sent between your Android app and PHP page is encrypted—no more plaintext sniffing!

2. Use HTTPS in Your Android App

Stick to popular Android networking libraries like OkHttp or Retrofit—they natively support HTTPS, so you won't have to mess with custom SSL configurations (as long as your PHP page's certificate is trusted, which free Let's Encrypt certs are). Here's a quick OkHttp example:

OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
    .add("user_data", userInput)
    .build();
Request request = new Request.Builder()
    .url("https://your-free-host-url.com/your-handler.php")
    .post(formBody)
    .build();

// Execute the request (use enqueue for async calls to avoid UI freezes)
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // Handle error
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // Handle success
    }
});

3. Add Request Signing (Optional but Impressive for Grades)

To prevent attackers from tampering with your request data, add a simple HMAC signature:

  • Client Side: Combine all your request parameters with a shared secret (e.g., "school-project-2024-secret"), hash it with HMAC-SHA256, and send the signature as an extra parameter.
  • Server Side: Recompute the signature using the same secret and parameters—if it doesn't match the received signature, reject the request.

Client-side Java snippet (using Apache Commons Codec for simplicity):

String params = "user_data=" + userInput + "school-project-2024-secret";
String signature = HmacUtils.hmacSha256Hex(params, "school-project-2024-secret");
// Add signature to your FormBody

Server-side PHP validation:

$sharedSecret = "school-project-2024-secret";
$receivedData = $_POST['user_data'];
$receivedSignature = $_POST['signature'];

$calculatedParams = "user_data=" . $receivedData . $sharedSecret;
$calculatedSignature = hash_hmac('sha256', $calculatedParams, $sharedSecret);

if ($calculatedSignature !== $receivedSignature) {
    http_response_code(403);
    exit("Invalid request—data may have been tampered with");
}
Encrypted Storage in Free MySQL

You don't need fancy paid tools here—use built-in MySQL functions or PHP's encryption libraries to store sensitive data as ciphertext.

1. MySQL Built-in AES Encryption

Free MySQL plans almost always support AES_ENCRYPT() and AES_DECRYPT(). Store your encryption key in a secure place (like a PHP config file with 600 permissions, so it can't be accessed via the web) instead of hardcoding it directly in your script.

PHP insertion example (using PDO to avoid SQL injection—always use prepared statements!):

$dbKey = file_get_contents('/path/to/secure/config/key.txt'); // Or hardcode for simplicity in school work
$userData = $_POST['user_data'];

$pdo = new PDO('mysql:host=your-db-host;dbname=your-db-name', 'db-user', 'db-pass');
$stmt = $pdo->prepare("INSERT INTO your_table (encrypted_data) VALUES (AES_ENCRYPT(?, ?))");
$stmt->execute([$userData, $dbKey]);

To retrieve and decrypt:

$stmt = $pdo->prepare("SELECT AES_DECRYPT(encrypted_data, ?) AS decrypted_data FROM your_table WHERE id = ?");
$stmt->execute([$dbKey, $recordId]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$plaintextData = $result['decrypted_data'];

2. PHP-side Encryption (More Flexible)

If your free MySQL plan has restrictions on encryption functions, encrypt the data in PHP first with openssl_encrypt() before storing it. You'll need to save the initialization vector (IV) along with the ciphertext—here's how:

PHP encryption:

$dbKey = "school-db-secret-2024";
$iv = random_bytes(16); // AES-256-CBC requires a 16-byte IV
$plaintext = $_POST['user_data'];

$ciphertext = openssl_encrypt($plaintext, 'AES-256-CBC', $dbKey, OPENSSL_RAW_DATA, $iv);
// Encode IV + ciphertext to base64 for easy storage
$storedData = base64_encode($iv . $ciphertext);

// Insert into database via prepared statement
$stmt = $pdo->prepare("INSERT INTO your_table (encrypted_data) VALUES (?)");
$stmt->execute([$storedData]);

Decryption in PHP:

$storedData = $result['encrypted_data'];
$decoded = base64_decode($storedData);
$iv = substr($decoded, 0, 16);
$ciphertext = substr($decoded, 16);

$plaintext = openssl_decrypt($ciphertext, 'AES-256-CBC', $dbKey, OPENSSL_RAW_DATA, $iv);
Quick Bonus Tips for Your Assignment
  • Always use prepared statements: This prevents SQL injection attacks, which is a basic security best practice and will earn you extra points.
  • Limit database user permissions: Create a MySQL user that only has access to INSERT, SELECT, and UPDATE (no DROP or ALTER). Most free hosts let you manage database users in their control panel.
  • Comment your code: Explain why you chose HTTPS, encryption methods, etc.—professors love seeing you understand the "why" behind your implementation.

内容的提问来源于stack exchange,提问作者KDN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:02:18