Orbital Root of Trust

Stay tuned

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.

jamie@example.com

Generating Secure Passwords with Verifiable Randomness from Space

Generating Secure Passwords with Verifiable Randomness from Space

Introduction

True randomness is vital for ensuring fairness and security within decentralized applications (dApps), especially in scenarios involving cryptography and gaming. SpaceComputer Orbitport addresses this critical need uniquely by leveraging satellite technology to offer authentic and tamper-proof randomness and secure compute, through its innovative infrastructure and APIs.

This comprehensive guide is beginner-friendly but designed specifically with TypeScript developers in mind. If you’d like to code along or implement the examples provided, having prior TypeScript knowledge — though not necessarily advanced — is recommended. However, if you’re here to read and understand the concepts, you don’t need any prior programming experience to gain valuable insights.

Get Developer Support on Telegram: Click Here

What is SpaceComputer?

SpaceComputer is a space-based digital sovereignty layer built as a cryptographically secure compute protocol for applications across the blockchain stack.

Each node in the network is a Space Trusted Execution Environment (SpaceTEE). The hardware infrastructure layer is based on satellites equipped with “crypto engines” and data modules, serving as the decentralized physical infrastructure network (DePIN) in orbit.

SpaceComputer architecture features a two-layer system: the Celestial Chain in space, serving as the ultimate authority for immutable data history, and the Uncelestial layer on Earth for fast transaction pre-finality. This brings high security guarantees based on tamper-resistant hardware orbiting in the isolated space environment, ensuring resilience even during terrestrial network outages.

SpaceComputer was founded by a team of experienced software and hardware researchers, entrepreneurs, and developers with expertise in both space and blockchain technology. The project aims to enable a space-native economy, envisioning a future where commerce and computation extend beyond Earth, supported by its innovative satellite-powered blockchain network.

Understanding Orbitport and cTRNG

Orbitport is the gateway to celestial compute services built on the SpaceComputer infrastructure. Leveraging SpaceComputer nodes, Orbitport enables decentralized systems to consume data from tamper-proof hardware on satellites that run in low Earth orbit. Orbitport opens the possibilities of orbital computing services that transcend the limitations of terrestrial infrastructure. Its key offerings include:

  • cTRNG (cosmic True Random Number Generator) : Employs data from cosmic radiation, detected via satellite instrumentation, to produce unbiased, cryptographically secure random numbers.
  • spaceTEE : Provides a secure and isolated environment designed specifically for the execution of sensitive, off-chain computational tasks, ensuring privacy and security.

Applications benefiting significantly from cTRNG’s unmatched randomness include online lotteries, gaming platforms, cryptographic key generation systems, blockchain-based smart contracts, and secure communication networks. For password generation, this cosmic randomness ensures passwords are truly unpredictable, mitigating risks from pseudo-random algorithms that could be exploited by attackers.

Authentication Flow Reference

To keep this article focused on the unique logic of Cosmic Cipher, we encourage you to read our previous post for a detailed, step-by-step guide to the authentication process: Building with SpaceComputer Orbitport: A Guide to Cosmic Randomness in Web3.

That guide covers the detailed walkthrough of the Orbitport authentication flow, including secure token management and server-side implementation, which we’ve reused here with minor adjustments for this password generator app.

Why Use Cosmic Randomness for Passwords?

Passwords are the first line of defense in digital security, but generating them with predictable algorithms can leave vulnerabilities. Traditional pseudo-random number generators (PRNGs) rely on deterministic processes, which sophisticated attackers might reverse-engineer or seed-predict. 

Enter cTRNG: by sourcing entropy from cosmic flares , unpredictable particle interactions in space, we create passwords with genuine, high-entropy randomness. This makes them resistant to brute-force attacks and ensures compliance with top security standards.

The beauty of this setup? The random seed comes from Orbitport’s satellite-powered servers, but all password generation logic runs locally on the client side. This hybrid approach lets you modify the logic freely, tweak character sets, enforce custom rules, or integrate with other tools , all without compromising the seed’s cosmic integrity. It’s like having a tamper-proof randomness oracle in orbit, beamed down for your app to remix as needed. 

Plus, we’ve added a fallback to Node.js’s crypto.randomBytes() for offline resilience, keeping things robust even if the stars (or servers) aren’t aligning.

Technical Implementation

(Get your API access key here: https://spacecomputer.deform.cc/ctrngearlyaccess )

We’ll create a Cosmic Cipher app, where users can generate unique and secure random passwords from the browser. Clone the demo branch to get started:

git clone -b demo git@github.com:spacecomputer-io/cosmic-cipher.git

All frontend components are already implemented. We will focus specifically on integrating API calls and password generation logic.

Fetching Random Seeds

Building on the auth foundation from our previous guide, we’ve implemented a streamlined API route to fetch cosmic random seeds. This happens server-side for security, using the valid access token to call Orbitport. Here’s the core logic from src/app/api/random/route.ts:

// src/app/api/random/route.ts

import { NextRequest, NextResponse } from "next/server";
import { getValidToken } from "@/lib/auth";
import { OrbitportSeedResponse } from "@/types/orbitport";

const ORBITPORT_API_URL = process.env.ORBITPORT_API_URL;

export async function GET(req: NextRequest) {
  let usedFallback = false;
  let data: OrbitportSeedResponse | null = null;

  try {
    if (!ORBITPORT_API_URL) throw new Error("Missing Orbitport API URL");

    // Create a response object for cookie setting
    const res = NextResponse.next();

    // Get valid token using our auth utility
    const accessToken = await getValidToken(req, res);
    if (!accessToken) {
      return NextResponse.json(
        { message: "Authentication failed" },
        { status: 401 }
      );
    }

    // Call downstream API with access token
    const response = await fetch(`${ORBITPORT_API_URL}/api/v1/services/trng`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error("Orbitport API error:", errorText);
      throw new Error(`API request failed: ${response.status}`);
    }

    data = await response.json();
  } catch (error) {
    console.warn("Using fallback random generation:", error);
    usedFallback = true;
    data = null;
  }

  return NextResponse.json({
    ...data,
    usedFallback,
  });
}

This endpoint securely retrieves a fresh cosmic seed, which we then use client-side for password crafting.

Local Password Generation Logic

Once the seed arrives, the magic happens locally. We’ve built a flexible generator that shuffles characters based on user inputs (length, min uppercase/lowercase/numbers/symbols) and the cosmic seed for entropy. 

Key function from src/lib/password-generator.ts:

// src/lib/password-generator.ts

// Core logic for generating a cosmic password from a seed
interface GenerateParams {
  length: number;
  minUpper: number;
  minLower: number;
  minNumbers: number;
  minSymbols: number;
  includeUpper: boolean;
  includeLower: boolean;
  includeNumbers: boolean;
  includeSymbols: boolean;
}

const CHARSETS = {
  uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  lowercase: "abcdefghijklmnopqrstuvwxyz",
  numbers: "0123456789",
  symbols: "!@#$%^&*+-=",
};

// Creates a deterministic random generator from cosmic seed
function createRandomGenerator(seed: string) {
  const seedBytes = new Uint8Array(Buffer.from(seed, "hex"));
  let position = 0;
  return (length: number): Uint8Array => {
    const result = new Uint8Array(length);
    for (let i = 0; i < length; i++) {
      result[i] = seedBytes[position % seedBytes.length];
      position++;
    }
    return result;
  };
}

export function generatePasswordFromSeed(seed: string, params: GenerateParams): string {
  const randomValues = createRandomGenerator(seed);
  const { length, minUpper, minLower, minNumbers, minSymbols, includeUpper, includeLower, includeNumbers, includeSymbols } = params;

  // Build character sets based on user selection
  const availableCharsets: { [key: string]: string } = {};
  if (includeUpper) availableCharsets.uppercase = CHARSETS.uppercase;
  if (includeLower) availableCharsets.lowercase = CHARSETS.lowercase;
  if (includeNumbers) availableCharsets.numbers = CHARSETS.numbers;
  if (includeSymbols) availableCharsets.symbols = CHARSETS.symbols;

  // Generate password meeting minimum requirements
  let password = "";
  if (includeUpper) for (let i = 0; i < minUpper; i++) password += availableCharsets.uppercase[randomValues(1)[0] % availableCharsets.uppercase.length];
  if (includeLower) for (let i = 0; i < minLower; i++) password += availableCharsets.lowercase[randomValues(1)[0] % availableCharsets.lowercase.length];
  if (includeNumbers) for (let i = 0; i < minNumbers; i++) password += availableCharsets.numbers[randomValues(1)[0] % availableCharsets.numbers.length];
  if (includeSymbols) for (let i = 0; i < minSymbols; i++) password += availableCharsets.symbols[randomValues(1)[0] % availableCharsets.symbols.length];

  // Fill remaining length with random chars
  const allAvailableChars = Object.values(availableCharsets).join("");
  const remainingLength = length - password.length;
  for (let i = 0; i < remainingLength; i++) {
    password += allAvailableChars[randomValues(1)[0] % allAvailableChars.length];
  }

  // Helper: Fisher-Yates shuffle using bytes for randomness
  const passwordArray = password.split("");
  for (let i = passwordArray.length - 1; i > 0; i--) {
    const j = randomValues(1)[0] % (i + 1);
    [passwordArray[i], passwordArray[j]] = [passwordArray[j], passwordArray[i]];
  }

  return passwordArray.join("");
}

This logic ensures requirements are met, then shuffles everything with the seed-derived bytes. Since it’s local, you can hack it — add emoji symbols for fun, or integrate mnemonic phrases for wallets. The displayed seed lets users verify the cosmic origin, adding a layer of trust and intrigue.

Implementing in Frontend

For easy integration in your React components, we’ve wrapped the cTRNG fetch in a hook at src/hooks/useOrbitport.ts. It handles seed fetching and authentication in one go, allowing us to focus on the frontend implementation of the password generator. We can look at src/app/page.tsx to see how it is done:

const { getRandomSeed } = useOrbitport();

const handleGenerate = async () => {
    setIsLoading(true);
    setError(null);
    setResult(null);

    try {
      // Fetch seed from API using the hook
      const seedResult = await getRandomSeed();

      // Generate password client-side using the seed
      const password = generatePasswordFromSeed(seedResult.data, {
        length: formData.length,
        minUpper: formData.minUpper,
        minLower: formData.minLower,
        minNumbers: formData.minNumbers,
        minSymbols: formData.minSymbols,
        includeUpper: characterTypes.uppercase,
        includeLower: characterTypes.lowercase,
        includeNumbers: characterTypes.numbers,
        includeSymbols: characterTypes.symbols,
      });

      setResult({
        password,
        seed: seedResult.data,
        usedFallback: seedResult.usedFallback,
      });
    } catch (err: unknown) {
      const apiError = err as ApiError;
      setError(apiError.message || "Failed to generate password");
    } finally {
      setIsLoading(false);
    }
  };

Now, just run npm run dev, head to http://localhost:3000, tweak your settings, and generate a password forged in the cosmos! 

Conclusion

Cosmic Cipher is more than just a password generator , it’s a demonstration of how space technology can be harnessed to solve real-world security challenges. By leveraging the cosmic randomness of Orbitport, Cosmic Cipher provides a level of security that is simply unmatched by traditional password generators. 

SpaceComputer Orbitport offers a secure, reliable, and genuinely random solution powered by satellite technology, with inherent robustness and tamper-resistant compute making it indispensable for applications requiring high levels of fairness, security, and resilience. As we continue to explore the possibilities of decentralized, space-based infrastructure, we’re excited to see what other innovative applications will emerge.

Resources

Latest issue