Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 6 min read

If Your Reseller Database Leaks, Your Panel Balance Goes With It: Encrypt API Keys in PHP With libsodium

By MD Fozla Rabbi, SEO Specialist A reseller site stores one thing that's basically cash. The provider API key. Whoever holds that key can place orders against your balance. No password needed. No second factor. And on

By MD Fozla Rabbi, SEO Specialist

A reseller site stores one thing that's basically cash. The provider API key.

Whoever holds that key can place orders against your balance. No password needed. No second factor. And on most small panels it sits in a settings table as plain text.

Now think about how databases leak on cheap hosting. A SQL injection in an old form. A backup zip left in public_html. A developer who copied the database to a laptop "just for testing". Any one of those is enough. Your key walks out the door with the rest.

So encrypt it at rest. PHP has shipped libsodium since 7.2. No Composer package. No OpenSSL flags to get wrong. About 70 lines.

Who this is for

Anyone running a site that resells from an upstream API. Maybe you buy from one SMM Reseller Panel and sell under your own brand. Maybe you juggle five providers. The pattern is identical.

I'll use the API layout from SMM Booster BD's API page as the example provider. It's the common "API v2" shape: POST /api/v2 with your key and an action. That key is what we're protecting.

What this fixes and what it doesn't

Let's be honest about scope first.

It protects you when:

  • Someone dumps your database through SQL injection
  • A backup file leaks
  • A staff member exports tables they shouldn't
  • Your hosting panel's phpMyAdmin gets brute-forced

It doesn't protect you when:

  • The attacker controls the whole server and can read your code plus the master key
  • Your own code logs the decrypted key somewhere
  • Someone steals an admin session and uses your site to place orders directly

Still worth it. Most real leaks are the first list, not the second.

Step 1: make a master key and keep it out of the database

Run this once on your own machine:

php -r "echo base64_encode(sodium_crypto_secretbox_keygen()), PHP_EOL;"

You get a 44-character string. That's the master key. Where it goes matters more than anything else in this post:

  • Best: an environment variable set in your hosting panel
  • Fine on shared hosting: a file above public_html, like /home/you/secrets/app.key, with chmod 600
  • Never: the database, your Git repo or anything a browser can request

Why not the database? Because the database is the thing we expect to leak. Locking a door and taping the key to it doesn't help much.

Step 2: the SecretBox class

<?php
// SecretBox.php: encrypt provider API keys before they touch the database.
// Needs PHP 7.4+ (libsodium is built in since 7.2).

final class SecretBox
{
    /** @var array<string,string> version => raw 32-byte key */
    private array $keys = [];
    private string $current;

    public function __construct(array $keys, string $current)
    {
        foreach ($keys as $version => $b64) {
            $raw = base64_decode($b64, true);
            if ($raw === false || strlen($raw) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
                throw new RuntimeException("Bad key for version $version");
            }
            $this->keys[$version] = $raw;
        }
        if (!isset($this->keys[$current])) {
            throw new RuntimeException("Unknown current key version $current");
        }
        $this->current = $current;
    }

    public static function newKey(): string
    {
        return base64_encode(sodium_crypto_secretbox_keygen());
    }

    public function encrypt(string $plain): string
    {
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $cipher = sodium_crypto_secretbox($plain, $nonce, $this->keys[$this->current]);
        return $this->current . ':' . base64_encode($nonce . $cipher);
    }

    public function decrypt(string $stored): string
    {
        [$version, $b64] = array_pad(explode(':', $stored, 2), 2, '');
        if (!isset($this->keys[$version])) {
            throw new RuntimeException("No key for version $version");
        }
        $raw = base64_decode($b64, true);
        if ($raw === false || strlen($raw) <= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
            throw new RuntimeException('Corrupted secret');
        }
        $nonce = substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $cipher = substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $plain = sodium_crypto_secretbox_open($cipher, $nonce, $this->keys[$version]);
        if ($plain === false) {
            throw new RuntimeException('Secret failed to decrypt (tampered or wrong key)');
        }
        return $plain;
    }

    public function needsRotation(string $stored): bool
    {
        return strpos($stored, $this->current . ':') !== 0;
    }

    public static function mask(string $plain): string
    {
        return str_repeat('โ€ข', 8) . substr($plain, -4);
    }
}

What each part does:

  • secretbox = encryption plus a tamper check. If anyone changes one byte of the stored value, decrypt fails loudly. It doesn't return garbage.
  • A fresh random nonce every time. Encrypt the same key twice and you get two different strings. Nobody can tell which providers share a key.
  • A version prefix like v1:. That tiny label is what makes key rotation painless later.
  • mask() for the admin screen. Show โ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ข9z8y so staff can confirm which key is saved without seeing it.

Step 3: save and load the provider key

<?php
require __DIR__ . '/SecretBox.php';

// Environment variable, or a file above public_html
$master = getenv('APP_SECRET_V1') ?: trim(file_get_contents('/home/you/secrets/app.key'));
$box = new SecretBox(['v1' => $master], 'v1');

// Saving (admin form)
$stmt = $pdo->prepare('UPDATE providers SET api_key = ? WHERE id = ?');
$stmt->execute([$box->encrypt(trim($_POST['api_key'])), $providerId]);

// Using it (order job)
$row = $pdo->query('SELECT api_url, api_key FROM providers WHERE id = 1')->fetch();
$key = $box->decrypt($row['api_key']);
$balance = callProvider($row['api_url'], $key, ['action' => 'balance']);
sodium_memzero($key); // wipe it from memory when done

Two small habits here. Decrypt only right before the API call. And wipe the variable straight after.

The column needs room. A 32-character API key becomes roughly 100 characters once encrypted and encoded. VARCHAR(255) is plenty. TEXT works too.

Step 4: test it

<?php
require __DIR__ . '/SecretBox.php';

$k1 = SecretBox::newKey();
$box = new SecretBox(['v1' => $k1], 'v1');

$stored = $box->encrypt('a1b2c3d4e5f6-provider-key-9z8y');
echo $stored, PHP_EOL;
echo $box->decrypt($stored), PHP_EOL;
echo SecretBox::mask($box->decrypt($stored)), PHP_EOL;

$bad = $stored;
$bad[10] = $bad[10] === 'A' ? 'B' : 'A'; // change one character
try {
    $box->decrypt($bad);
} catch (RuntimeException $e) {
    echo 'tamper caught: ', $e->getMessage(), PHP_EOL;
}

Output on PHP 8.3:

v1:VoUkoVoAFNYc4TuoNmtsF5k2K3eWvwJiRHMKp6m5KpI7ipHnwZiVeRbKSriplfwaorsZFyUp+6wODKlQJ03mN3VCzFj4Ug==
a1b2c3d4e5f6-provider-key-9z8y
โ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ข9z8y
tamper caught: Secret failed to decrypt (tampered or wrong key)

Your encrypted string will look different. That's the random nonce doing its job.

Step 5: rotate the master key without downtime

Say a developer leaves. Or the key file ended up in a backup you don't trust. Time for a new master key.

Generate v2 the same way. Load both keys but write with v2:

<?php
$box = new SecretBox(['v1' => $oldKey, 'v2' => $newKey], 'v2');

foreach ($pdo->query('SELECT id, api_key FROM providers') as $row) {
    if ($box->needsRotation($row['api_key'])) {
        $fresh = $box->encrypt($box->decrypt($row['api_key']));
        $pdo->prepare('UPDATE providers SET api_key = ? WHERE id = ?')
            ->execute([$fresh, $row['id']]);
    }
}

Reads keep working the whole time because the box still knows v1. Once every row says v2:, delete the old key. And then rotate the provider API key itself too, if you think it might have leaked. Encryption can't un-leak a key that's already out.

Gotchas on shared hosting

  • Check the extension. extension_loaded('sodium') should return true. It's built in from PHP 7.2. But a few old hosts still run 7.1 or older. Upgrade if you can.
  • Back up the master key separately. Lose it and every stored API key becomes noise. Keep a copy in your password manager. Not next to the database backup.
  • Don't log the key. Error handlers love to dump variables. Make sure exception logs never print $key.
  • Same idea for other secrets. Payment gateway secrets, SMTP passwords and webhook tokens all fit the same class.

A clean public catalog doesn't need any of this. Prices and service names are meant to be seen, like the list at https://smmbooster.bd/services. The secret is only the key that pays for those orders.

Recap

  • Treat provider API keys like cash
  • Encrypt them with sodium_crypto_secretbox before saving
  • Keep the master key outside the database and outside public_html
  • Prefix stored values with a version so rotation is easy
  • Mask keys in the admin UI and wipe them from memory after use
  • Rotate the provider key itself if you suspect a leak

Running a reseller site on shared hosting? Tell me in the comments how you store secrets today. I'm curious how many of us still have them in a settings table.

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.