generating public and private key on page and on page two encrypt the data through input by user of public key and on page three decrypt the data using uploading private key
Laravel 9 code for generating public and private keys, encrypting the user's input with the public key, and decrypting it with the private key:
Page 1: Key Generation
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
// Generate a new public/private key pair
$keyPair = openssl_pkey_new([
"digest_alg" => "sha256",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
]);
// Get the private key
openssl_pkey_export($keyPair, $privateKey);
// Get the public key
$keyDetails = openssl_pkey_get_details($keyPair);
$publicKey = $keyDetails["key"];
// Store the keys in the session for later use
session()->put("privateKey", $privateKey);
session()->put("publicKey", $publicKey);
// Display the public key for the user to copy and paste
echo "<pre>" . $publicKey . "</pre>";
Page 2: Data Encryption
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
// Get the user's input from the request
$input = $request->input("data");
// Get the public key from the session
$publicKey = session()->get("publicKey");
// Encrypt the input using the public key
$encrypted = Crypt::encryptString($input, $publicKey);
// Display the encrypted data for the user to copy and paste
echo "<pre>" . $encrypted . "</pre>";
Page 3: Data Decryption
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
// Get the encrypted data from the request
$encrypted = $request->input("data");
// Get the private key from the session
$privateKey = session()->get("privateKey");
// Decrypt the data using the private key
$decrypted = Crypt::decryptString($encrypted, $privateKey);
// Display the decrypted data for the user to view
echo "<pre>" . $decrypted . "</pre>";
Top comments (0)