Debug School

rakesh kumar
rakesh kumar

Posted on

Generate and download a public and private key in laravel9

Steps 1:

<a href="{{ url('/generate-keys') }}" class="btn btn-primary">Generate Keys</a>
Enter fullscreen mode Exit fullscreen mode

Steps 2:

Route::get('/generate-keys', function () {
    $privateKey = openssl_pkey_new();
    openssl_pkey_export($privateKey, $privateKeyString);
    $publicKey = openssl_pkey_get_details($privateKey);
    $publicKeyString = $publicKey['key'];

    $filename = 'my_keys.txt';
    $handle = fopen($filename, 'w');
    fwrite($handle, $privateKeyString . PHP_EOL . $publicKeyString);
    fclose($handle);

    return response()->download($filename);
});
Enter fullscreen mode Exit fullscreen mode

=============================OR============================

Image description

Image description

Image description

ANOTHER METHOD

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>";
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

ANOTHER METHOD

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

// Display a button for the user to click
echo "<button onclick='generateKeys()'>Generate Keys</button>";

// JavaScript function to generate the keys and display the public key
echo "<script>
    function generateKeys() {
        fetch('/generate-keys')
        .then(response => response.text())
        .then(publicKey => {
            document.body.innerHTML += '<pre>' + publicKey + '</pre>';
        });
    }
</script>";

// Route to handle the key generation request
Route::get('/generate-keys', function () {
    // 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);

    // Return the public key as plain text
    return $publicKey;
});
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Image description

This code displays a "Generate Keys" button for the user to click. When the button is clicked, a JavaScript function sends a request to the server to generate the keys and retrieve the public key. The public key is then displayed on the page in a

 element.

Note that in a real-world application, you would want to handle errors and security concerns more thoroughly. You might also want to store the keys in a more secure manner, such as in a database or encrypted on disk.

ANOTHER METHOD

generating and downloading public and private keys retrieve them as a ZIP archive

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

// Display a button for the user to click
echo "<button onclick='generateKeys()'>Generate Keys and Download</button>";

// JavaScript function to generate the keys and download the files
echo "<script>
    function generateKeys() {
        fetch('/generate-keys')
        .then(response => response.blob())
        .then(blob => {
            // Create a temporary URL for the blob
            const url = URL.createObjectURL(blob);

            // Create an anchor element to download the file
            const a = document.createElement('a');
            a.href = url;
            a.download = 'keys.zip';
            a.click();

            // Revoke the temporary URL
            URL.revokeObjectURL(url);
        });
    }
</script>";

// Route to handle the key generation request
Route::get('/generate-keys', function () {
    // 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"];

    // Create a ZIP archive containing the keys
    $zip = new ZipArchive();
    $zipName = tempnam(sys_get_temp_dir(), 'keys');
    $zip->open($zipName, ZipArchive::CREATE);
    $zip->addFromString('private.pem', $privateKey);
    $zip->addFromString('public.pem', $publicKey);
    $zip->close();

    // Return the ZIP archive as a response
    return response()->download($zipName, 'keys.zip')->deleteFileAfterSend(true);
});

Image description

Image description

Image description

Image description

Laravel 9 code to pass a route when a button is pressed
Image description

Top comments (0)