DEV Community

HarmonyOS
HarmonyOS

Posted on

Secure Random Number Generation in HarmonyOS

Read the original article:Secure Random Number Generation in HarmonyOS

Context

Secure random number generation is essential for any application that handles sensitive data or requires cryptographic operations. Unlike regular random number generators, secure random numbers must be truly unpredictable to prevent security vulnerabilities.

Description

Standard random functions like Math.random() are dangerous for security purposes because:

  • They produce predictable sequences
  • Lack proper entropy sources
  • Can be reverse-engineered by attackers This creates risks in authentication, encryption, and other security-sensitive features.

Solution / Approach

HarmonyOS provides cryptographically secure random number generation through:

  1. cryptoFramework.createRandom() - Creates a secure generator instance
  2. generateRandom() / generateRandomSync() - Generates unpredictable bytes
  3. Support for both small and large random values (1 byte to INT_MAX)

Basic Examples

1. One-Line Random Number Generation

import { cryptoFramework } from '@kit.CryptoArchitectureKit';

// Generate 10 random bytes (80 bits)
const randomBytes = cryptoFramework.createRandom().generateRandomSync(10).data;
console.log("Random bytes:", randomBytes);
Enter fullscreen mode Exit fullscreen mode

2. Creating Encryption Keys

async function generateEncryptionKey() {
  const secureRandom = cryptoFramework.createRandom();
  const key = await secureRandom.generateRandom(32); // 256-bit AES key
  console.log("Encryption key:", key.data);
}
generateEncryptionKey();
Enter fullscreen mode Exit fullscreen mode

3. Generating Secure PIN Codes

function generateSecurePin() {
  const random = cryptoFramework.createRandom();
  const bytes = random.generateRandomSync(4).data; // 4 bytes = 32 bits
  const pin = (bytes[0] % 9000) + 1000; // 4-digit PIN (1000-9999)
  console.log("Secure PIN:", pin);
}
generateSecurePin();
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Stops encryption breaking
  • Eliminates predictability attacks
  • Meets security compliance requirements

Additional Resources

Written by Simay Ayberik

Top comments (0)