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:
-
cryptoFramework.createRandom()- Creates a secure generator instance -
generateRandom()/generateRandomSync()- Generates unpredictable bytes - 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);
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();
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();
Key Takeaways
- Stops encryption breaking
- Eliminates predictability attacks
- Meets security compliance requirements
Top comments (0)