QRNG API Documentation

Production-ready quantum random number generation with cryptographic proofs, blockchain anchoring, and post-quantum signatures. This documentation covers everything you need to integrate QRNG API into your applications.

Table of Contents

Quick Start

Generate your first quantum random bytes in 60 seconds:

1. Get Your API Key

Sign up at qrngapi.com/signup and get your API key from the Dashboard.

2. Make Your First Request

curl -X POST https://qrngapi.com/api/random \
  -H "Content-Type: application/json" \
  -H "X-API-Key: qrng_your_api_key_here" \
  -d '{
    "bytes": 32,
    "format": "hex"
  }'

3. Response

{
  "entropy": "a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456",
  "bytes": 32,
  "format": "hex",
  "method": "photon",
  "timestamp": "2025-01-15T12:00:00.000Z",
  "signature": "base64_encoded_ed25519_signature...",
  "publicKey": "base64_encoded_public_key...",
  "hash": "sha3_256_hash_of_entropy..."
}

Authentication

All API requests require authentication using an API key. Include your key in the request header:

X-API-Key: qrng_xxxxxxxxxxxxxxxxxxxxxxxxxxxx
API Key Format: All API keys start with qrng_ followed by 32 alphanumeric characters.

Security Best Practices

REST API Endpoints

Base URL: https://qrngapi.com/api

POST /api/random

Generate quantum random bytes with cryptographic proof and optional blockchain anchoring.

Request Headers

HeaderRequiredDescription
Content-TypeYesMust be application/json
X-API-KeyYesYour API key

Request Body Parameters

ParameterTypeRequiredDefaultDescription
bytesintegerYes-Number of random bytes to generate (1-1024)
formatstringNohexOutput format: hex, base64, or array
methodstringNoautoQuantum method: photon, tunneling, vacuum, thermal
signatureTypestringNoed25519Signature algorithm: ed25519, dilithium2, dilithium3, dilithium5
notarizebooleanNofalseAnchor to blockchain (Pro+ tiers)
chainstringNopolygonBlockchain: polygon or avalanche

Response Fields

FieldTypeDescription
entropystring/arrayThe generated random data in requested format
bytesintegerNumber of bytes generated
formatstringOutput format used
methodstringQuantum method used
timestampstringISO 8601 timestamp
signaturestringCryptographic signature (base64)
publicKeystringPublic key for verification (base64)
hashstringSHA3-256 hash of entropy
signatureTypestringSignature algorithm used
txHashstringBlockchain transaction hash (if notarized)

Example: Generate 64 bytes as base64

curl -X POST https://qrngapi.com/api/random \
  -H "Content-Type: application/json" \
  -H "X-API-Key: qrng_your_api_key" \
  -d '{
    "bytes": 64,
    "format": "base64",
    "method": "photon"
  }'

Example: Generate with Post-Quantum Signature (Enterprise)

curl -X POST https://qrngapi.com/api/random \
  -H "Content-Type: application/json" \
  -H "X-API-Key: qrng_your_enterprise_key" \
  -d '{
    "bytes": 32,
    "format": "hex",
    "signatureType": "dilithium3"
  }'

POST /api/verify

Verify the cryptographic signature of previously generated entropy.

Request Body

ParameterTypeRequiredDescription
entropystringYesThe entropy value to verify
signaturestringYesThe signature from generation response
publicKeystringYesThe public key from generation response
timestampstringNoOriginal timestamp for additional validation

Response

{
  "valid": true,
  "entropy": "a1b2c3d4...",
  "verifiedAt": "2025-01-15T12:01:00.000Z"
}
Note: The /api/verify endpoint currently supports Ed25519 signatures only. For Dilithium (post-quantum) signatures, use client-side verification with the SDK or verification libraries.

GET /api/health

Check API health status and quantum hardware availability.

Response

{
  "status": "healthy",
  "timestamp": "2025-01-15T12:00:00.000Z",
  "hardware": {
    "photon": { "status": "online", "latency": 12 },
    "tunneling": { "status": "online", "latency": 15 },
    "vacuum": { "status": "online", "latency": 18 },
    "thermal": { "status": "maintenance", "latency": null }
  },
  "uptime": 99.99
}

GET /api/usage

Get your current usage statistics and quota information. Requires authentication.

Response

{
  "tier": "pro",
  "period": {
    "start": "2025-01-01T00:00:00.000Z",
    "end": "2025-01-31T23:59:59.999Z"
  },
  "usage": {
    "requests": 15420,
    "bytes": 493440,
    "limit": 100000
  },
  "rateLimit": {
    "requestsPerMinute": 300,
    "remaining": 298,
    "resetsAt": "2025-01-15T12:01:00.000Z"
  }
}

WebSocket Streaming

For real-time continuous entropy streaming, connect via WebSocket:

Connection URL

wss://qrngapi.com/ws/entropy?apiKey=YOUR_API_KEY

Subscribe to Entropy Stream

{
  "action": "subscribe",
  "bytes": 16,
  "interval": 1000,
  "format": "hex"
}

Stream Response (continuous)

{
  "type": "entropy",
  "data": {
    "entropy": "a1b2c3d4e5f6789012345678901234ab",
    "bytes": 16,
    "format": "hex",
    "method": "photon",
    "timestamp": "2025-01-15T12:00:01.000Z",
    "sequence": 1
  }
}

Unsubscribe

{
  "action": "unsubscribe"
}

WebSocket Events

Event TypeDescription
entropyEntropy data packet
subscribedConfirmation of subscription
unsubscribedConfirmation of unsubscription
errorError message
rateLimitRate limit warning

JavaScript WebSocket Example

const ws = new WebSocket('wss://qrngapi.com/ws/entropy?apiKey=YOUR_API_KEY');

ws.onopen = () => {
  console.log('Connected to QRNG API');
  ws.send(JSON.stringify({
    action: 'subscribe',
    bytes: 32,
    interval: 1000,
    format: 'hex'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === 'entropy') {
    console.log('Received entropy:', data.data.entropy);
  }
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = () => {
  console.log('Disconnected from QRNG API');
};

Signature Verification

Every entropy response includes a cryptographic signature that proves the data was generated by QRNG API. Here's how to verify signatures in different languages:

JavaScript (Node.js)

import { verify } from '@noble/ed25519';

async function verifyEntropy(response) {
  const { entropy, signature, publicKey, timestamp } = response;
  
  // Reconstruct the signed message
  const message = new TextEncoder().encode(
    JSON.stringify({ entropy, timestamp })
  );
  
  // Decode base64 signature and public key
  const sig = Buffer.from(signature, 'base64');
  const pubKey = Buffer.from(publicKey, 'base64');
  
  // Verify the signature
  const isValid = await verify(sig, message, pubKey);
  return isValid;
}

Python

from nacl.signing import VerifyKey
from nacl.exceptions import BadSignature
import base64
import json

def verify_entropy(response):
    entropy = response['entropy']
    signature = base64.b64decode(response['signature'])
    public_key = base64.b64decode(response['publicKey'])
    timestamp = response['timestamp']
    
    # Reconstruct the signed message
    message = json.dumps({'entropy': entropy, 'timestamp': timestamp}).encode()
    
    # Verify
    verify_key = VerifyKey(public_key)
    try:
        verify_key.verify(message, signature)
        return True
    except BadSignature:
        return False

Go

package main

import (
    "crypto/ed25519"
    "encoding/base64"
    "encoding/json"
)

func verifyEntropy(response map[string]interface{}) bool {
    entropy := response["entropy"].(string)
    timestamp := response["timestamp"].(string)
    
    sig, _ := base64.StdEncoding.DecodeString(response["signature"].(string))
    pubKey, _ := base64.StdEncoding.DecodeString(response["publicKey"].(string))
    
    message, _ := json.Marshal(map[string]string{
        "entropy": entropy,
        "timestamp": timestamp,
    })
    
    return ed25519.Verify(pubKey, message, sig)
}

Post-Quantum Cryptography

QRNG API supports post-quantum signatures using the NIST-standardized Dilithium algorithm (FIPS 204). These signatures are resistant to attacks from quantum computers.

Available Signature Types

TypeSecurity LevelSignature SizeTier Required
ed25519~128-bit classical64 bytesAll tiers
dilithium2~128-bit quantum~2.4 KBPro+
dilithium3~192-bit quantum~3.3 KBEnterprise
dilithium5~256-bit quantum~4.6 KBEnterprise

Using Post-Quantum Signatures

curl -X POST https://qrngapi.com/api/random \
  -H "Content-Type: application/json" \
  -H "X-API-Key: qrng_enterprise_key" \
  -d '{
    "bytes": 32,
    "signatureType": "dilithium3"
  }'

Verifying Dilithium Signatures

Use one of these libraries for client-side verification:

// JavaScript - Verifying Dilithium signatures
import { ml_dsa65 } from '@noble/post-quantum';

const isValid = ml_dsa65.verify(
  publicKey,
  message,
  signature
);

Blockchain Anchoring

Optionally anchor your entropy to a public blockchain for immutable proof of generation time and content.

Supported Blockchains

ChainNetworkConfirmation TimeTier Required
PolygonMainnet~2 secondsPro+
AvalancheC-Chain~1 secondEnterprise

Request with Blockchain Notarization

curl -X POST https://qrngapi.com/api/random \
  -H "Content-Type: application/json" \
  -H "X-API-Key: qrng_pro_key" \
  -d '{
    "bytes": 32,
    "notarize": true,
    "chain": "polygon"
  }'

Response with Transaction Hash

{
  "entropy": "a1b2c3d4...",
  "bytes": 32,
  "signature": "...",
  "txHash": "0x1234567890abcdef...",
  "chain": "polygon",
  "blockNumber": 12345678
}

Official SDKs

Production-ready client libraries with full TypeScript/type support:

Python

pip install qrng-api
from qrng import QRNGClient

client = QRNGClient(api_key="qrng_your_api_key")

# Generate random bytes
result = client.random(bytes=32, format="hex")
print(result.entropy)

# Verify signature
is_valid = client.verify(result)
print(f"Signature valid: {is_valid}")

# Stream entropy
for entropy in client.stream(bytes=16, interval=1.0):
    print(entropy.data)

JavaScript / TypeScript

npm install @qrng/sdk
import { QRNGClient } from '@qrng/sdk';

const client = new QRNGClient({ apiKey: 'qrng_your_api_key' });

// Generate random bytes
const result = await client.random({ bytes: 32, format: 'hex' });
console.log(result.entropy);

// Verify signature
const isValid = await client.verify(result);
console.log(`Signature valid: ${isValid}`);

// Stream entropy
const stream = client.stream({ bytes: 16, interval: 1000 });
stream.on('entropy', (data) => console.log(data.entropy));
stream.start();

Go

go get github.com/qrng-api/go-sdk
package main

import (
    "fmt"
    "github.com/qrng-api/go-sdk/qrng"
)

func main() {
    client := qrng.NewClient("qrng_your_api_key")
    
    // Generate random bytes
    result, err := client.Random(qrng.RandomRequest{
        Bytes:  32,
        Format: "hex",
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(result.Entropy)
    
    // Verify signature
    valid, _ := client.Verify(result)
    fmt.Printf("Signature valid: %v\n", valid)
}

Java

<dependency>
  <groupId>io.qrng</groupId>
  <artifactId>qrng-api-sdk</artifactId>
  <version>1.0.0</version>
</dependency>
import io.qrng.QRNGClient;
import io.qrng.RandomResult;

public class Example {
    public static void main(String[] args) {
        QRNGClient client = new QRNGClient("qrng_your_api_key");
        
        // Generate random bytes
        RandomResult result = client.random()
            .bytes(32)
            .format("hex")
            .execute();
        
        System.out.println(result.getEntropy());
        
        // Verify signature
        boolean valid = client.verify(result);
        System.out.println("Signature valid: " + valid);
    }
}

Rust

cargo add qrng-api
use qrng_api::QRNGClient;

#[tokio::main]
async fn main() -> Result<(), Box> {
    let client = QRNGClient::new("qrng_your_api_key");
    
    // Generate random bytes
    let result = client.random()
        .bytes(32)
        .format("hex")
        .send()
        .await?;
    
    println!("{}", result.entropy);
    
    // Verify signature
    let valid = client.verify(&result).await?;
    println!("Signature valid: {}", valid);
    
    Ok(())
}

Rate Limits

Rate limits are enforced per API key based on your subscription tier:

TierRequests/minMax Bytes/requestWebSocket StreamsMonthly Quota
Free1064110,000 requests
Starter602562100,000 requests
Pro30051251,000,000 requests
Enterprise1000+1024UnlimitedCustom

Rate Limit Headers

Every response includes rate limit information in headers:

HeaderDescription
X-RateLimit-LimitMaximum requests per minute
X-RateLimit-RemainingRemaining requests in current window
X-RateLimit-ResetUnix timestamp when limit resets
Rate Limit Exceeded: When you exceed your rate limit, you'll receive a 429 Too Many Requests response. Wait until the reset time before retrying.

Error Handling

All errors return a consistent JSON format:

{
  "error": "Invalid API key format",
  "code": "INVALID_API_KEY",
  "status": 401,
  "timestamp": "2025-01-15T12:00:00.000Z",
  "requestId": "req_abc123xyz"
}

Error Codes

HTTP StatusCodeDescription
400BAD_REQUESTInvalid request parameters
400INVALID_BYTESBytes must be between 1 and 1024
400INVALID_FORMATFormat must be hex, base64, or array
401INVALID_API_KEYAPI key is missing or invalid
401API_KEY_EXPIREDAPI key has been revoked
403TIER_LIMITFeature not available for your tier
403QUOTA_EXCEEDEDMonthly quota exceeded
429RATE_LIMITToo many requests
500INTERNAL_ERRORServer error - contact support
503HARDWARE_UNAVAILABLEQuantum hardware temporarily unavailable

Error Handling Example

try {
  const result = await client.random({ bytes: 32 });
} catch (error) {
  switch (error.code) {
    case 'RATE_LIMIT':
      // Wait and retry
      await sleep(error.retryAfter * 1000);
      break;
    case 'QUOTA_EXCEEDED':
      // Upgrade plan or wait for next billing cycle
      console.log('Monthly quota exceeded');
      break;
    case 'HARDWARE_UNAVAILABLE':
      // Retry with different method or wait
      break;
    default:
      console.error('Unexpected error:', error.message);
  }
}

Support

Need help integrating QRNG API? We're here to help!

Enterprise Support: Enterprise customers receive dedicated support with guaranteed response times. Contact us for more information.