▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/encryption-keys/code-examples$ _

Encryption Key Generation Code Examples

AES keys and RSA key pairs in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

Each example produces a 256-bit and a 128-bit AES key, printed as hex (64 and 32 characters) and Base64, plus a 2048-bit RSA key pair exported as PEM or DER. The guide explains key sizes, the random source, and how IVs and nonces differ from keys; each language section then covers the APIs and their pitfalls. Prefer no code? The interactive Encryption key generator does the same in the browser.

Symmetric keys are just random bytes

AES (FIPS 197) accepts keys of exactly 16, 24 or 32 bytes, for AES-128, AES-192 and AES-256. A key is nothing more than that many bytes from a cryptographically secure generator. Hex or Base64 is only a way to store or paste it; decode it back to raw bytes before handing it to a cipher. AES-128 is not practically breakable today; AES-256 is the usual choice because it keeps a large margin against future attacks, including Grover's algorithm on a quantum computer, and many compliance rules ask for it. ChaCha20-Poly1305 also takes a 32-byte random key.

Here a secure source is mandatory: every example uses one (random_bytes(), crypto.randomBytes(), secrets.token_bytes(), KeyGenerator with SecureRandom, Aes.GenerateKey(), Crypto++ AutoSeededRandomPool, SecureRandom.random_bytes, crypto/rand). A key drawn from Math.random() or mt_rand() is predictable once the generator state is known, and mt_rand() is seeded from only 32 bits, so such a key has at most 32 bits of real strength whatever its length.

Keys, IVs and nonces are different things

The key is secret and reused for many messages. The IV or nonce is not secret, is stored next to the ciphertext, and must be fresh for every encryption:

  • AES-GCM: 12-byte (96-bit) nonce. It must never repeat under the same key; a repeat reveals the XOR of the two plaintexts and lets an attacker forge tags. With random nonces, NIST SP 800-38D limits one key to 232 encryptions. The 16-byte tag must be stored and checked.
  • AES-CBC: 16-byte IV that must be unpredictable, so random, not a counter. CBC has no integrity protection; add an HMAC (encrypt-then-MAC) or prefer GCM.
  • XChaCha20-Poly1305: 24-byte nonce, large enough to pick at random without counting messages.

RSA key pairs

RSA keys are not random bytes: the library searches for two large random primes. Use 2048 bits as the minimum, which NIST SP 800-57 rates at 112-bit security; 3072 bits gives 128-bit security for data that must stay protected past 2030. Keep the public exponent at 65537. RSA encrypts only short data: with OAEP and SHA-256, a 2048-bit key takes at most 190 bytes. For files, generate a random AES key, encrypt the data with it, and encrypt only the AES key with RSA. For new designs, X25519 (key agreement) and Ed25519 (signatures) give shorter keys and faster operations.

Common mistakes

  • Using a password as the key. A typed password has far less than 128 bits of entropy and the wrong length. Derive a key with Argon2id, scrypt or PBKDF2 (OWASP suggests 600,000 iterations of PBKDF2-HMAC-SHA256) and a random 16-byte salt.
  • Passing the hex string as the key. A 64-character hex string is 64 bytes of ASCII, not 32 bytes of key. PHP openssl_encrypt() silently truncates or zero-pads keys of the wrong length, so the mistake never raises an error.
  • Fixed or reused IVs. A constant IV in CBC leaks which messages start the same way; in GCM a reused nonce breaks both confidentiality and authentication.
  • Keeping keys next to the data. A key in the same database or repository as the ciphertext protects nothing. Use a KMS or HSM, encrypt data keys with a key-encryption key (envelope encryption), and store a key ID with each ciphertext so keys can be rotated.

Common Use Cases

  • Field-level encryption of personal data in databases
  • File, backup and object-storage encryption with AES-256-GCM
  • Data keys for envelope encryption with AWS KMS, Google Cloud KMS or HashiCorp Vault
  • RSA key pairs for signing documents and verifying software releases
  • Key wrapping for end-to-end encrypted messaging and file sharing

Encryption Key Generation Code Examples in PHP

Learn how to generate AES encryption keys and RSA key pairs in PHP using OpenSSL and random_bytes() for cryptographically secure encryption.

<?php
// AES-256 Encryption Key Generation
$aes_key = random_bytes(32); // 256 bits
$aes_key_hex = bin2hex($aes_key);
echo "AES-256 Key (Hex): " . $aes_key_hex . "\n";

// AES-128 Encryption Key
$aes_128_key = bin2hex(random_bytes(16)); // 128 bits
echo "AES-128 Key (Hex): " . $aes_128_key . "\n";

// RSA Key Pair Generation (2048-bit)
$config = [
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
];

$res = openssl_pkey_new($config);
openssl_pkey_export($res, $private_key);
$public_key = openssl_pkey_get_details($res)["key"];

echo "Private Key:\n" . $private_key . "\n";
echo "Public Key:\n" . $public_key . "\n";

// Base64 encode for storage
$encoded_key = base64_encode($aes_key);
echo "AES Key (Base64): " . $encoded_key;

How it works in PHP

This code demonstrates AES and RSA key generation in PHP. For symmetric encryption (AES), we use random_bytes() with 32 bytes (256 bits) for AES-256 or 16 bytes (128 bits) for AES-128. The bin2hex() converts binary to hexadecimal for easy storage. For asymmetric encryption (RSA), openssl_pkey_new() generates a key pair with configurable bit length (2048 or 4096 recommended). openssl_pkey_export() extracts the private key in PEM format, while openssl_pkey_get_details() retrieves the public key. Keys should be stored securely (environment variables, key vaults) and never hardcoded.

Sample output

AES-256 Key (Hex): a3f5d8c2e1b4f7a9c6d3e8b2f5a1c4d7e9b3f6a2c5d8e1b4f7a9c6d3e8b2f5a1
AES-128 Key (Hex): c7e2f5a9d3b8e1c4f7a2d6b9e3c5f8a1
Private Key:
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC8...
-----END PRIVATE KEY-----
Public Key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvP...
-----END PUBLIC KEY-----
AES Key (Base64): o/XYwuG096nG0+iy9aHE1+mz9qLF2OG096nG0+iy9aE=

PHP notes

  • Pass the raw $aes_key bytes to openssl_encrypt(), not $aes_key_hex, and set OPENSSL_RAW_DATA if you handle encoding yourself.
  • For AES-256-GCM, get the nonce length with openssl_cipher_iv_length('aes-256-gcm') (12) and pass a $tag variable to receive the 16-byte tag.
  • Sodium (bundled since PHP 7.2) has sodium_crypto_aead_xchacha20poly1305_ietf_keygen(), which avoids nonce-length decisions entirely.

Encryption Key Generation Code Examples in JavaScript

Generate AES and RSA encryption keys in JavaScript/Node.js using the crypto module and Web Crypto API for secure encryption.

// Node.js - AES & RSA Key Generation
const crypto = require('crypto');

// AES-256 Key Generation
const aesKey = crypto.randomBytes(32); // 256 bits
const aesKeyHex = aesKey.toString('hex');
console.log('AES-256 Key (Hex):', aesKeyHex);

// AES-128 Key
const aes128Key = crypto.randomBytes(16).toString('hex');
console.log('AES-128 Key (Hex):', aes128Key);

// RSA Key Pair Generation (2048-bit)
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

console.log('Private Key:\n', privateKey);
console.log('Public Key:\n', publicKey);

// Base64 encoding for storage
const aesKeyBase64 = aesKey.toString('base64');
console.log('AES Key (Base64):', aesKeyBase64);

// Web Crypto API (Browser)
// async function generateWebCryptoKey() {
//   const key = await crypto.subtle.generateKey(
//     { name: 'AES-GCM', length: 256 },
//     true,
//     ['encrypt', 'decrypt']
//   );
//   return key;
// }

How it works in JavaScript

Node.js provides crypto.randomBytes() for generating cryptographically secure random keys. For AES-256, use 32 bytes (256 bits); for AES-128, use 16 bytes (128 bits). Convert to hex or base64 for storage. crypto.generateKeyPairSync() creates RSA key pairs with configurable modulus length (2048 or 4096 bits). The publicKeyEncoding and privateKeyEncoding options control output format (PEM, DER). For browser environments, use the Web Crypto API (crypto.subtle.generateKey()) which returns CryptoKey objects suitable for encryption operations.

Sample output

AES-256 Key (Hex): f3a7d2e5c1b8f4a9d6c3e7b2f5a8c1d4e7b9f2a5c8d1e4b7f3a6d2e5c1b8f4a9
AES-128 Key (Hex): d2f5a8c1e4b7f3a9d6c2e5b8f1a4c7d2
Private Key:
 -----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDH...
-----END PRIVATE KEY-----
Public Key:
 -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx8...
-----END PUBLIC KEY-----
AES Key (Base64): 86fS5cG49KnWw+ey9ajB1Oe58qXI0eS389ptLlwbj0o=

JavaScript notes

  • Node.js 15+ also offers crypto.generateKeySync('aes', { length: 256 }), which returns a KeyObject instead of a Buffer.
  • With Web Crypto, pass extractable: false to crypto.subtle.generateKey() when the key never needs to leave the browser; then even page scripts cannot export it.
  • generateKeyPairSync() blocks the event loop for tens to hundreds of milliseconds; use the async generateKeyPair() in servers.

Encryption Key Generation Code Examples in Python

Generate AES and RSA encryption keys in Python using the cryptography library for secure encryption and decryption.

# Install: pip install cryptography
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.fernet import Fernet
import secrets

# Fernet key: 32 bytes = 16-byte HMAC-SHA256 key + 16-byte AES-128-CBC key
fernet_key = Fernet.generate_key()
print(f"Fernet Key (Base64): {fernet_key.decode()}")

# Raw AES-256 Key (32 bytes)
aes_256_key = secrets.token_bytes(32)
aes_256_hex = aes_256_key.hex()
print(f"AES-256 Key (Hex): {aes_256_hex}")

# AES-128 Key (16 bytes)
aes_128_key = secrets.token_hex(16)  # Returns hex string
print(f"AES-128 Key (Hex): {aes_128_key}")

# RSA Key Pair Generation (2048-bit)
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)

# Export private key
private_pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)

# Export public key
public_key = private_key.public_key()
public_pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

print(f"Private Key:\n{private_pem.decode()}")
print(f"Public Key:\n{public_pem.decode()}")

How it works in Python

Python's cryptography library provides robust encryption key generation. Fernet.generate_key() creates a URL-safe base64-encoded 32-byte key for Fernet symmetric encryption (uses AES-128-CBC internally with HMAC authentication). For raw AES keys, use secrets.token_bytes() (32 bytes for AES-256, 16 for AES-128) or secrets.token_hex() for hexadecimal output. rsa.generate_private_key() creates RSA key pairs with customizable key size (2048 or 4096 bits). The serialization module exports keys in PEM format. Use NoEncryption() for unencrypted private keys or BestAvailableEncryption(password) to password-protect private keys.

Sample output

Fernet Key (Base64): hkRpGpM0I11HWw1DVyYTuu7wKrUs0OR8we1UKyn6lic=
AES-256 Key (Hex): c7e2f5a9d3b8e1c4f7a2d6b9e3c5f8a1d4b7e9c2f5a8d1b4e7f9c3a6d8e2f5a9
AES-128 Key (Hex): f3a7d2e5c1b8f4a9d6c3e7b2f5a8c1d4
Private Key:
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC5...
-----END PRIVATE KEY-----
Public Key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAub...
-----END PUBLIC KEY-----

Python notes

  • A Fernet key is 32 bytes split into a 16-byte HMAC-SHA256 key and a 16-byte AES-128-CBC key, so it is not an AES-256 key.
  • For raw AES-GCM, AESGCM.generate_key(bit_length=256) and a 12-byte os.urandom(12) nonce per message are the cryptography equivalents.
  • Replace NoEncryption() with BestAvailableEncryption(b"passphrase") before writing a private key to disk.

Encryption Key Generation Code Examples in Java

Generate AES and RSA encryption keys in Java using KeyGenerator and KeyPairGenerator from the javax.crypto package.

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.*;
import java.util.Base64;

public class EncryptionKeyGenerator {
    public static void main(String[] args) throws Exception {
        // AES-256 Key Generation
        KeyGenerator aesKeyGen = KeyGenerator.getInstance("AES");
        aesKeyGen.init(256, new SecureRandom());
        SecretKey aesKey = aesKeyGen.generateKey();

        byte[] aesKeyBytes = aesKey.getEncoded();
        String aesKeyHex = bytesToHex(aesKeyBytes);
        String aesKeyBase64 = Base64.getEncoder().encodeToString(aesKeyBytes);

        System.out.println("AES-256 Key (Hex): " + aesKeyHex);
        System.out.println("AES-256 Key (Base64): " + aesKeyBase64);

        // AES-128 Key
        aesKeyGen.init(128);
        SecretKey aes128Key = aesKeyGen.generateKey();
        System.out.println("AES-128 Key (Hex): " + bytesToHex(aes128Key.getEncoded()));

        // RSA Key Pair Generation (2048-bit)
        KeyPairGenerator rsaKeyGen = KeyPairGenerator.getInstance("RSA");
        rsaKeyGen.initialize(2048, new SecureRandom());
        KeyPair keyPair = rsaKeyGen.generateKeyPair();

        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        System.out.println("Private Key (Base64): " +
            Base64.getEncoder().encodeToString(privateKey.getEncoded()));
        System.out.println("Public Key (Base64): " +
            Base64.getEncoder().encodeToString(publicKey.getEncoded()));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }
}

How it works in Java

Java's KeyGenerator class generates symmetric keys (AES). Call getInstance("AES") to get an AES key generator, then init() with key size (128, 192, or 256 bits) and a SecureRandom instance for cryptographic randomness. generateKey() returns a SecretKey object, and getEncoded() retrieves the raw bytes. For asymmetric encryption, KeyPairGenerator.getInstance("RSA") creates RSA key pairs. initialize() sets the modulus length (2048 or 4096 bits), and generateKeyPair() returns a KeyPair containing private and public keys. Base64 encoding is standard for key storage and transmission.

Sample output

AES-256 Key (Hex): a7d2e5c1b8f4a9d6c3e7b2f5a8c1d4e7b9f2a5c8d1e4b7f3a6d2e5c1b8f4a9d6
AES-256 Key (Base64): p9LlwbjGnWw+ey9ajB1Oe58qXI0eS389ptLlwbj0qtY=
AES-128 Key (Hex): c2f5a8d1e4b7f3a9d6c2e5b8f1a4c7d2
Private Key (Base64): MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDN...
Public Key (Base64): MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzf...

Java notes

  • AES-256 works out of the box since JDK 8u161 (and 7u171), when the unlimited-strength policy became the default; the separate JCE download is only needed on older updates.
  • For GCM, use Cipher.getInstance("AES/GCM/NoPadding") with new GCMParameterSpec(128, nonce) and a 12-byte nonce; plain "AES" means ECB mode.
  • getEncoded() returns PKCS#8 for private keys and X.509 SubjectPublicKeyInfo for public keys; add PEM headers and 64-character lines for PEM.

Encryption Key Generation Code Examples in C#

Generate AES and RSA encryption keys in C# using System.Security.Cryptography for secure encryption and decryption.

using System;
using System.Security.Cryptography;
using System.Text;

class EncryptionKeyGenerator
{
    static void Main()
    {
        // AES-256 Key Generation
        using (Aes aes = Aes.Create())
        {
            aes.KeySize = 256;
            aes.GenerateKey();

            string aesKeyHex = BitConverter.ToString(aes.Key).Replace("-", "");
            string aesKeyBase64 = Convert.ToBase64String(aes.Key);

            Console.WriteLine($"AES-256 Key (Hex): {aesKeyHex}");
            Console.WriteLine($"AES-256 Key (Base64): {aesKeyBase64}");
        }

        // AES-128 Key (manual, with RandomNumberGenerator)
        byte[] aes128Key = new byte[16]; // 128 bits
        RandomNumberGenerator.Fill(aes128Key);
        Console.WriteLine($"AES-128 Key (Hex): {BitConverter.ToString(aes128Key).Replace("-", "")}");

        // RSA Key Pair Generation (2048-bit)
        using (RSA rsa = RSA.Create(2048))
        {
            // Export private key
            string privateKeyXml = rsa.ToXmlString(true);
            byte[] privateKeyBytes = rsa.ExportPkcs8PrivateKey();
            string privateKeyBase64 = Convert.ToBase64String(privateKeyBytes);

            // Export public key
            string publicKeyXml = rsa.ToXmlString(false);
            byte[] publicKeyBytes = rsa.ExportSubjectPublicKeyInfo();
            string publicKeyBase64 = Convert.ToBase64String(publicKeyBytes);

            Console.WriteLine($"Private Key (Base64): {privateKeyBase64}");
            Console.WriteLine($"Public Key (Base64): {publicKeyBase64}");
        }
    }
}

How it works in C#

Aes.Create() returns the platform AES implementation; setting KeySize = 256 and calling GenerateKey() fills aes.Key with 32 random bytes. For a key without an Aes object, RandomNumberGenerator.Fill() writes secure random bytes into an existing buffer, replacing the obsolete RNGCryptoServiceProvider. RSA.Create(2048) generates the key pair; ExportPkcs8PrivateKey() and ExportSubjectPublicKeyInfo() produce the standard DER encodings that OpenSSL and other languages read, which the Base64 output shows.

Sample output

AES-256 Key (Hex): D2F5A8C1E4B7F3A9D6C2E5B8F1A4C7D2E9C3F6A8D1B4E7F2A5C8D1E4B7F3A9D6
AES-256 Key (Base64): 0vWoweS386nWwuW48aTH0unD9qjRtOfypcjR5LfzqdY=
AES-128 Key (Hex): F3A7D2E5C1B8F4A9D6C3E7B2F5A8C1D4
Private Key (Base64): MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC8...
Public Key (Base64): MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvP...

C# notes

  • RNGCryptoServiceProvider is obsolete since .NET 6 (warning SYSLIB0023); use the static RandomNumberGenerator methods.
  • .NET 7+ adds ExportPkcs8PrivateKeyPem() and ExportSubjectPublicKeyInfoPem() for PEM output.
  • Use AesGcm (.NET Core 3.0+) for authenticated encryption, and protect stored keys with the Data Protection API or Azure Key Vault.

Encryption Key Generation Code Examples in C++

Generate AES and RSA encryption keys in C++ using the Crypto++ library for secure cryptographic operations.

#include <iostream>
#include <cryptopp/cryptlib.h>
#include <cryptopp/rijndael.h>
#include <cryptopp/modes.h>
#include <cryptopp/files.h>
#include <cryptopp/osrng.h>
#include <cryptopp/rsa.h>
#include <cryptopp/hex.h>
#include <cryptopp/base64.h>

using namespace CryptoPP;

int main() {
    AutoSeededRandomPool rng;

    // AES-256 Key Generation
    byte aes256Key[AES::MAX_KEYLENGTH]; // 32 bytes
    rng.GenerateBlock(aes256Key, sizeof(aes256Key));

    std::string aes256Hex;
    HexEncoder hexEncoder(new StringSink(aes256Hex));
    hexEncoder.Put(aes256Key, sizeof(aes256Key));
    hexEncoder.MessageEnd();

    std::cout << "AES-256 Key (Hex): " << aes256Hex << std::endl;

    // AES-128 Key
    byte aes128Key[16];
    rng.GenerateBlock(aes128Key, 16);

    std::string aes128Hex;
    StringSource(aes128Key, 16, true, new HexEncoder(new StringSink(aes128Hex)));
    std::cout << "AES-128 Key (Hex): " << aes128Hex << std::endl;

    // RSA Key Pair Generation (2048-bit)
    RSA::PrivateKey privateKey;
    privateKey.GenerateRandomWithKeySize(rng, 2048);

    RSA::PublicKey publicKey(privateKey);

    // Export private key (DER format)
    std::string privateKeyDer;
    StringSink privKeySink(privateKeyDer);
    privateKey.DEREncode(privKeySink);
    privKeySink.MessageEnd();

    std::string privateKeyBase64;
    StringSource(privateKeyDer, true,
        new Base64Encoder(new StringSink(privateKeyBase64), false));

    std::cout << "Private Key (Base64): " << privateKeyBase64 << std::endl;

    return 0;
}

How it works in C++

Crypto++ AutoSeededRandomPool seeds itself from the operating system and generates key bytes with GenerateBlock(). AES::MAX_KEYLENGTH is 32 bytes (AES-256) and AES::DEFAULT_KEYLENGTH is 16 bytes (AES-128), so the constant decides the key size. Encoders are fed through StringSource with pumpAll = true, which calls MessageEnd() and flushes the final Base64 group. GenerateRandomWithKeySize() creates a 2048-bit RSA private key, the public key is built from it, and DEREncode() writes the private key as DER.

Sample output

AES-256 Key (Hex): C7E2F5A9D3B8E1C4F7A2D6B9E3C5F8A1D4B7E9C2F5A8D1B4E7F9C3A6D8E2F5A9
AES-128 Key (Hex): F3A7D2E5C1B8F4A9D6C3E7B2F5A8C1D4
Private Key (Base64): MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDH...

C++ notes

  • AES::DEFAULT_KEYLENGTH is 16, not 32; use AES::MAX_KEYLENGTH or a literal 32 for AES-256.
  • Crypto++ is a compiled library: install libcrypto++-dev (Debian/Ubuntu) and link with -lcryptopp.
  • Store keys in SecByteBlock, which zeroes its memory on destruction, rather than a plain array.

Encryption Key Generation Code Examples in Ruby

Generate AES and RSA encryption keys in Ruby using OpenSSL and SecureRandom for secure encryption and decryption.

require 'openssl'
require 'securerandom'
require 'base64'

# AES-256 Key Generation
aes_256_key = SecureRandom.random_bytes(32) # 256 bits
aes_256_hex = aes_256_key.unpack1('H*')
aes_256_base64 = Base64.strict_encode64(aes_256_key)

puts "AES-256 Key (Hex): #{aes_256_hex}"
puts "AES-256 Key (Base64): #{aes_256_base64}"

# AES-128 Key
aes_128_key = SecureRandom.hex(16) # Returns hex string (16 bytes)
puts "AES-128 Key (Hex): #{aes_128_key}"

# RSA Key Pair Generation (2048-bit)
rsa_key = OpenSSL::PKey::RSA.new(2048)

private_key_pem = rsa_key.to_pem
public_key_pem = rsa_key.public_key.to_pem

puts "Private Key:\n#{private_key_pem}"
puts "Public Key:\n#{public_key_pem}"

# Export in DER format (binary)
private_key_der = rsa_key.to_der
public_key_der = rsa_key.public_key.to_der

private_key_base64 = Base64.strict_encode64(private_key_der)
puts "Private Key (Base64): #{private_key_base64}"

# Password-protected private key
encrypted_key = rsa_key.private_to_pem(OpenSSL::Cipher.new('AES-256-CBC'), 'password')
puts "Encrypted Private Key:\n#{encrypted_key}"

How it works in Ruby

Ruby's SecureRandom module provides cryptographically secure random generation. Use SecureRandom.random_bytes(n) for raw bytes (32 for AES-256, 16 for AES-128) or SecureRandom.hex(n) for hexadecimal strings. unpack1('H*') converts bytes to hex. For RSA, OpenSSL::PKey::RSA.new(bits) generates a key pair with the specified bit length (2048 or 4096). to_pem exports keys in PEM format (ASCII), while to_der exports in DER format (binary). To password-protect private keys, pass a cipher and password to to_pem (e.g., OpenSSL::Cipher.new('AES-256-CBC')).

Sample output

AES-256 Key (Hex): d2f5a8c1e4b7f3a9d6c2e5b8f1a4c7d2e9c3f6a8d1b4e7f2a5c8d1e4b7f3a9d6
AES-256 Key (Base64): 0vWoweS386nWwuW48aTH0unD9qjRtOfypcjR5LfzqdY=
AES-128 Key (Hex): f3a7d2e5c1b8f4a9d6c3e7b2f5a8c1d4
Private Key:
-----BEGIN RSA PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC9...
-----END RSA PRIVATE KEY-----
Public Key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvd...
-----END PUBLIC KEY-----

Ruby notes

  • OpenSSL::Cipher.new('aes-256-gcm').random_key returns a key of the right length for that cipher, and random_iv a nonce.
  • to_pem with a cipher writes the legacy OpenSSL PEM encryption, whose key derivation is a single MD5 pass; private_to_pem(cipher, password) (openssl gem 3.0+, bundled since Ruby 3.1) writes PKCS#8 with PBKDF2.
  • In Rails, ActiveSupport::MessageEncryptor and Active Record encryption handle IVs and authentication for you.

Encryption Key Generation Code Examples in Go

Generate AES and RSA encryption keys in Go using crypto/rand and crypto/rsa packages for secure encryption.

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/base64"
    "encoding/hex"
    "encoding/pem"
    "fmt"
    "log"
)

func main() {
    // AES-256 Key Generation
    aes256Key := make([]byte, 32) // 256 bits
    if _, err := rand.Read(aes256Key); err != nil {
        log.Fatal(err)
    }

    aes256Hex := hex.EncodeToString(aes256Key)
    aes256Base64 := base64.StdEncoding.EncodeToString(aes256Key)

    fmt.Println("AES-256 Key (Hex):", aes256Hex)
    fmt.Println("AES-256 Key (Base64):", aes256Base64)

    // AES-128 Key
    aes128Key := make([]byte, 16)
    rand.Read(aes128Key)
    fmt.Println("AES-128 Key (Hex):", hex.EncodeToString(aes128Key))

    // RSA Key Pair Generation (2048-bit)
    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        log.Fatal(err)
    }

    // Export private key (PKCS8 format)
    privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
    if err != nil {
        log.Fatal(err)
    }

    privateKeyPem := pem.EncodeToMemory(&pem.Block{
        Type:  "PRIVATE KEY",
        Bytes: privateKeyBytes,
    })

    // Export public key
    publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
    if err != nil {
        log.Fatal(err)
    }

    publicKeyPem := pem.EncodeToMemory(&pem.Block{
        Type:  "PUBLIC KEY",
        Bytes: publicKeyBytes,
    })

    fmt.Println("Private Key:\n", string(privateKeyPem))
    fmt.Println("Public Key:\n", string(publicKeyPem))
}

How it works in Go

Go's crypto/rand package provides cryptographically secure random generation via rand.Read(), which fills a byte slice with random data from the OS's CSPRNG. For AES keys, create a 32-byte slice (AES-256) or 16-byte slice (AES-128) and populate with rand.Read(). Use hex.EncodeToString() or base64.StdEncoding.EncodeToString() for encoding. For RSA, rsa.GenerateKey(rand.Reader, bits) creates a private key with the specified bit length (2048 or 4096). x509.MarshalPKCS8PrivateKey() and x509.MarshalPKIXPublicKey() export keys to standard formats, which are then PEM-encoded with pem.EncodeToMemory() for storage.

Sample output

AES-256 Key (Hex): c7e2f5a9d3b8e1c4f7a2d6b9e3c5f8a1d4b7e9c2f5a8d1b4e7f9c3a6d8e2f5a9
AES-256 Key (Base64): x+L1qdO44cT3ota548X4odS36cL1qNG05/nDptji9ak=
AES-128 Key (Hex): f3a7d2e5c1b8f4a9d6c3e7b2f5a8c1d4
Private Key:
 -----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDK...
-----END PRIVATE KEY-----
Public Key:
 -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyv...
-----END PUBLIC KEY-----

Go notes

  • Since Go 1.24, rand.Read never returns an error, so the unchecked AES-128 call is safe there; on older versions check it like the AES-256 one.
  • For AES-GCM, cipher.NewGCM(block) uses a 12-byte nonce (gcm.NonceSize()); prepend it to the ciphertext.
  • x509.EncryptPEMBlock is deprecated and insecure; keep private keys in a KMS or secret manager, or write encrypted PKCS#8 with OpenSSL.

Try the Interactive Generator

Need values right now rather than code? The Encryption key generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE ENCRYPTION KEY GENERATOR →