Crypto API
The Crypto API provides cryptographic functionality similar to the Web Crypto API standard. It includes methods for generating random values, creating UUIDs, and performing cryptographic operations.
Overview
The crypto
global object provides access to cryptographic functions including
random number generation, hashing, and other cryptographic operations through
the SubtleCrypto interface.
Methods
crypto.randomUUID()
Generates a random UUID (Universally Unique Identifier) string.
Returns: string
- A random UUID in the format
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Example:
const uuid = crypto.randomUUID();
console.log("Generated UUID:", uuid);
// Output: Generated UUID: f47ac10b-58cc-4372-a567-0e02b2c3d479
crypto.getRandomValues(array)
Fills the provided typed array with cryptographically secure random values.
Parameters:
array
- A typed array (Uint8Array, Uint16Array, Uint32Array, etc.) to fill with random values
Returns: The same array that was passed in, now filled with random values
Example:
const buffer = new Uint8Array(16);
crypto.getRandomValues(buffer);
console.log("Random bytes:", buffer);
// Output: Random bytes: Uint8Array(16) [123, 45, 67, 89, ...]
// Works with different typed arrays
const uint32Buffer = new Uint32Array(4);
crypto.getRandomValues(uint32Buffer);
console.log("Random 32-bit values:", uint32Buffer);
SubtleCrypto Interface
The crypto.subtle
property provides access to the SubtleCrypto interface for
advanced cryptographic operations.
crypto.subtle.digest(algorithm, data)
Generates a digest of the given data using the specified algorithm.
Parameters:
algorithm
- The hash algorithm to use (e.g., "SHA-1", "SHA-256", "SHA-384", "SHA-512")data
- The data to hash (Uint8Array, ArrayBuffer, or other binary data)
Returns: Promise<string>
- A promise that resolves to the hex-encoded hash
Note: The current implementation returns a hex string instead of an ArrayBuffer for convenience. This is non-standard behavior that may change in future versions.
Example:
const encoder = new TextEncoder();
const data = encoder.encode("Hello, World!");
crypto.subtle.digest("SHA-256", data)
.then((hash) => {
console.log("SHA-256 hash:", hash);
// Output: SHA-256 hash: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
});
// Using async/await
const hash = await crypto.subtle.digest("SHA-256", data);
console.log("Hash:", hash);
Supported Hash Algorithms
- SHA-1: Legacy algorithm, not recommended for security-critical applications
- SHA-256: Recommended for most applications
- SHA-384: Part of the SHA-2 family
- SHA-512: Part of the SHA-2 family, provides the highest security
Key Generation (Future)
The SubtleCrypto interface will support additional operations in future versions:
generateKey()
- Generate cryptographic keysimportKey()
- Import keys from external sourcesexportKey()
- Export keys for external usesign()
- Create digital signaturesverify()
- Verify digital signaturesencrypt()
- Encrypt datadecrypt()
- Decrypt data
Usage Examples
Basic Random Number Generation
// Generate a random byte array
const randomBytes = new Uint8Array(32);
crypto.getRandomValues(randomBytes);
// Generate a random UUID
const sessionId = crypto.randomUUID();
Hashing Data
async function hashPassword(password: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(password);
return await crypto.subtle.digest("SHA-256", data);
}
const hashedPassword = await hashPassword("mySecretPassword");
console.log("Hashed password:", hashedPassword);
File Integrity Verification
async function verifyFileIntegrity(
fileData: Uint8Array,
expectedHash: string,
): Promise<boolean> {
const actualHash = await crypto.subtle.digest("SHA-256", fileData);
return actualHash === expectedHash;
}
// Usage
const fileBuffer = new Uint8Array([/* file data */]);
const isValid = await verifyFileIntegrity(fileBuffer, "expected-hash-value");
Security Considerations
Use appropriate algorithms: Use SHA-256 or higher for security-critical applications
Random number quality:
crypto.getRandomValues()
provides cryptographically secure random numbers suitable for security purposesUUID uniqueness: UUIDs generated by
crypto.randomUUID()
are Version 4 (random) UUIDs with proper entropyData handling: Always use proper encoding (TextEncoder) when hashing strings
Browser Compatibility
The Crypto API in Andromeda follows the Web Crypto API standard where possible, making it easier to port code between environments.
See Also
- Text Encoding API - For proper string-to-bytes conversion
- Web Standards Compliance - For compatibility information