How to Generate Your Public and Private Keys

How to Generate Your Public and Private Keys

Info
This guide explains how to generate an RSA 2048-bit key pair in PKCS#8 format, and prepare them for use in API requests. RSA is an asymmetric encryption algorithm where the public key is used for encryption, and the private key for decryption. This setup used to encrypt data sent to via the API.

Important Notes:

  • Security: Generate keys on a secure machine. Never share or expose the private key.

  • PKCS#8 Format: This is a standard for encoding private keys.

  • Base64 Encoding: We'll encode the entire PEM public key (including headers like -----BEGIN PUBLIC KEY----- and footers) in base64 for transmission.

  • Libraries: Use cryptographic libraries in your language. Avoid implementing RSA from scratch.

  • Usage: After generation, use the public key in each request that requires it, and decrypt the results of document/download with the private key.

Step 1: Generate the RSA Key Pair

  • Create a 2048-bit RSA private key and derive the corresponding public key.

  • Ensure the private key is in PKCS#8 format.

Step 2: Export and Store the Private Key

  • Save the private key in PEM format to a file (e.g., private.pem).

  • Optionally, encrypt it with a passphrase for added security.

Step 3: Export and Base64-Encode the Public Key

  • Export the public key in PEM format.

  • Base64-encode the entire PEM string.

  • This encoded string can be sent in the publicKey parameter of your API request body.

Step 4: Integrate into Requests

  • Include the base64-encoded public key in your HTTP request body, e.g. { "publicKey": "<base64_string>" }.

  • Use the private key for decryption operations (see “Document Decryption Guide”). LINK

Step 5: Best Practices

  • Regenerate keys periodically or if compromised.

  • Validate keys after generation (e.g., check if they can encrypt/decrypt a test message).

  • Handle errors gracefully (e.g., invalid key formats).

  • For production, use hardware security modules (HSMs) for key storage.

Code Examples

PHP

  1. <?php

    function generateRsaKeyPair($privateKeyFile = 'private.pem', $passphrase = null) {
        // Step 1: Generate RSA 2048-bit key pair
        $config = [
            'digest_alg' => 'sha256',
            'private_key_bits' => 2048,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ];
        $res = openssl_pkey_new($config);
        
        if (!$res) {
            throw new Exception('Failed to generate key pair: ' . openssl_error_string());
        }

        // Step 2: Export private key to PEM file (PKCS#8 format)
        $exportOptions = $passphrase ? ['encrypt_key' => $passphrase] : [];
        if (!openssl_pkey_export_to_file($res, $privateKeyFile, $passphrase, $config)) {
            throw new Exception('Failed to export private key: ' . openssl_error_string());
        }

        // Step 3: Export public key in PEM format
        $publicKeyPem = openssl_pkey_get_details($res)['key'];

        // Base64-encode the public key PEM
        $publicKeyBase64 = base64_encode($publicKeyPem);

        // Free the resource
        openssl_pkey_free($res);

        return $publicKeyBase64;
    }

    // Example usage
    try {
        $base64PublicKey = generateRsaKeyPair('private.pem', 'your_secure_passphrase'); // Omit passphrase for unencrypted
        echo "Base64-Encoded Public Key:\n" . $base64PublicKey . PHP_EOL;
        
        // For API request (e.g., using cURL)
        $requestBody = json_encode(['publicKey' => $base64PublicKey]);
        // Send $requestBody in your HTTP POST request
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . PHP_EOL;
    }

JavaScript (Node.js)


  1. const crypto = require('crypto');

    const fs = require('fs');


    function generateRsaKeyPair(privateKeyFile = 'private.pem', passphrase = null) {

      // Step 1: Generate RSA 2048-bit key pair

      const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {

        modulusLength: 2048,

        publicKeyEncoding: { type: 'spki', format: 'pem' },

        privateKeyEncoding: {

          type: 'pkcs8',

          format: 'pem',

          cipher: passphrase ? 'aes-256-cbc' : undefined,

          passphrase: passphrase || undefined

        }

      });


      // Step 2: Store private key in PEM file

      fs.writeFileSync(privateKeyFile, privateKey);


      // Step 3: Base64-encode the public key PEM

      const publicKeyBase64 = Buffer.from(publicKey).toString('base64');


      return publicKeyBase64;

    }


    // Example usage

    const base64PublicKey = generateRsaKeyPair('private.pem', 'your_secure_passphrase'); // Omit passphrase for unencrypted

    console.log('Base64-Encoded Public Key:', base64PublicKey);


    // For API request (e.g., using fetch)

    const requestBody = JSON.stringify({ publicKey: base64PublicKey });

    // fetch('https://api.example.com', { method: 'POST', body: requestBody, headers: { 'Content-Type': 'application/json' } });


    • Related Articles

    • How to generate the Authorization header

      This guide provides a detailed explanation of how to generate an Authorization header for an API request using cryptographic operations. The process involves creating a JSON request body, hashing an API key with SHA-256, and then using that hash to ...
    • Document Decryption Guide

      This guide provides a step-by-step explanation of the decryption process for the encrypted file in the result of document/download. The scheme combines RSA (asymmetric encryption) to encrypt a symmetric key and AES (symmetric encryption) in CBC mode ...
    • Implement Document Signing via Evrotrust Application

      This guide provides a step-by-step process for integrating the Evrotrust API to enable document signing via the Evrotrust mobile app. The flow involves checking user status, sending documents for signing, handling callbacks, checking status ...
    • User Guide - Evrotrust Support Portal - Zoho Desk

      Тable of Contents Summary & Overview Purpose of This Guide How to Use the Evrotrust Support Portal 1. Registration, Login & Forgotten Password 1.1 First-Time Access 1.2 How to Log In 1.3 How to Reset a Password 2. Navigating the Portal 2.1 Home ...