PHP中如何用libsodium实现私钥加密存储至文件(替代OpenSSL)
Hey Leon, nice to hear you're making the switch to libsodium—it's a fantastic upgrade for security and performance compared to older OpenSSL workflows. Let's break down how to export your key pairs to files, just like you did with OpenSSL, whether you're using libsodium's modern asymmetric algorithms or sticking with RSA.
First, a quick note: Libsodium is optimized for modern primitives like Ed25519 (for signing) and X25519 (for key exchange) rather than RSA. These are faster, more secure, and easier to work with, so I'd recommend leaning into them if you don't have a hard requirement for RSA. But I'll cover both scenarios below.
1. Exporting Ed25519/X25519 Key Pairs
Libsodium's keys are raw binary data, which means you can write them directly to files, or encode them as Base64 (similar to PEM files in OpenSSL) for easier storage or sharing.
Example: Generate and Save Ed25519 Key Pair
<?php // Generate a new Ed25519 signing key pair $keyPair = sodium_crypto_sign_keypair(); // Extract the secret and public keys from the pair $secretKey = sodium_crypto_sign_secretkey($keyPair); $publicKey = sodium_crypto_sign_publickey($keyPair); // Option 1: Save raw binary keys (smaller, faster to process) file_put_contents('/your/path/secret_key.bin', $secretKey); file_put_contents('/your/path/public_key.bin', $publicKey); // Option 2: Save Base64-encoded keys (human-readable, like PEM) $encodedSecret = base64_encode($secretKey); $encodedPublic = base64_encode($publicKey); file_put_contents('/your/path/secret_key.txt', $encodedSecret); file_put_contents('/your/path/public_key.txt', $encodedPublic); ?>
To load these keys back into your application later:
<?php // Load raw binary secret key and reconstruct the pair $secretKey = file_get_contents('/your/path/secret_key.bin'); $keyPair = sodium_crypto_sign_secretkey_to_keypair($secretKey); // Or load Base64-encoded key $encodedSecret = file_get_contents('/your/path/secret_key.txt'); $secretKey = base64_decode($encodedSecret); $keyPair = sodium_crypto_sign_secretkey_to_keypair($secretKey); ?>
2. Exporting RSA Key Pairs (If You Need RSA)
Libsodium supports RSA for "sealing" (encrypting data to a public key) via sodium_crypto_box_seal, but it doesn't natively handle PEM encoding like OpenSSL. If you need to export RSA keys in PEM format (the same way you did with OpenSSL), you'll need to bridge libsodium's raw keys with PHP's OpenSSL functions.
Example: Generate RSA Key Pair with Libsodium, Export to PEM
<?php // Generate an RSA key pair for sealing (2048-bit is standard) $rsaKeyPair = sodium_crypto_box_seal_keypair(); // Extract raw binary public and secret keys $rsaPublicKey = sodium_crypto_box_seal_publickey($rsaKeyPair); $rsaSecretKey = sodium_crypto_box_seal_secretkey($rsaKeyPair); // Convert raw secret key to OpenSSL format and export as PEM $opensslSecret = openssl_pkey_get_private([ 'key' => $rsaSecretKey, 'type' => OPENSSL_KEYTYPE_RSA, ]); openssl_pkey_export($opensslSecret, $pemSecret); file_put_contents('/your/path/rsa_secret.pem', $pemSecret); // Convert raw public key to OpenSSL format and export as PEM $opensslPublic = openssl_pkey_get_public([ 'key' => $rsaPublicKey, 'type' => OPENSSL_KEYTYPE_RSA, ]); $pemPublic = openssl_pkey_get_details($opensslPublic)['key']; file_put_contents('/your/path/rsa_public.pem', $pemPublic); ?>
A quick tip: If you're working with RSA heavily, you might want to generate the keys directly with OpenSSL first, then import them into libsodium—this gives you more control over PEM formatting and key parameters.
Important Best Practices
- Secure Your Secret Keys: Always set strict file permissions (like
chmod 600on secret key files) so only your application can read them. Never commit secret keys to version control! - Choose the Right Algorithm: Unless you have a legacy requirement, go with Ed25519/X25519—they're more secure and performant than RSA.
- Raw vs Encoded: Raw binary keys are more efficient, but Base64/PEM are easier to handle in text-based workflows.
Hope this clears things up and helps you transition smoothly to libsodium!
内容的提问来源于stack exchange,提问作者Itergator

