A cross-platform cryptography library for Node.js, React.js, and React Native with an identical API across all platforms. Built on the Web Crypto API standard for maximum compatibility and security.
- Universal API - Same method names work on Node.js, browsers, and React Native
- Zero Dependencies - Uses native Web Crypto API (Node.js & browsers)
- Secure by Default - AES-GCM encryption, PBKDF2 password hashing
- Easy to Use - Simple async/await API
- TypeScript Support - Full type definitions included
- Lightweight - Minimal bundle size
- Battle-tested - Comprehensive test suite
npm install cross-crypto
React Native requires an additional polyfill:
npm install react-native-quick-crypto
Follow the react-native-quick-crypto setup guide for platform-specific configuration.
const crypto = require('cross-crypto');
async function example() {
// Generate a key
const key = await crypto.generateKey();
// Encrypt a message
const encrypted = await crypto.encrypt('Hello World', key);
// Decrypt it back
const decrypted = await crypto.decrypt(encrypted, key);
console.log(decrypted); // 'Hello World'
}
example();
Generate a cryptographically secure AES-256 encryption key.
Returns: Promise<string> - Base64 encoded key
const key = await crypto.generateKey();
// Store this key securely!
Encrypt a string using AES-GCM.
Parameters:
plaintext(string) - Text to encryptkey(string) - Base64 encoded encryption key
Returns: Promise<Object> - Object containing ciphertext, iv, and algorithm
const encrypted = await crypto.encrypt('Secret message', key);
// Returns: { ciphertext: '...', iv: '...', algorithm: 'AES-GCM' }
Decrypt encrypted data.
Parameters:
encryptedData(Object) - Object returned fromencrypt()key(string) - Base64 encoded decryption key (same as encryption)
Returns: Promise<string> - Decrypted plaintext
const decrypted = await crypto.decrypt(encrypted, key);
Encrypt a JavaScript object (automatically converts to JSON).
Parameters:
obj(Object) - Object to encryptkey(string) - Base64 encoded encryption key
Returns: Promise<Object> - Encrypted data
const user = { id: 123, name: 'John', email: 'john@example.com' };
const encrypted = await crypto.encryptObject(user, key);
Decrypt and parse a JavaScript object.
Parameters:
encryptedData(Object) - Encrypted object datakey(string) - Base64 encoded decryption key
Returns: Promise<Object> - Decrypted object
const decrypted = await crypto.decryptObject(encrypted, key);
Hash a password using PBKDF2 with 100,000 iterations.
Parameters:
password(string) - Password to hashsalt(string, optional) - Base64 encoded salt (generates new if not provided)
Returns: Promise<Object> - Object containing hash, salt, iterations, and algorithm
const hashResult = await crypto.hash('MyPassword123');
// Store hashResult.hash and hashResult.salt in your database
Verify a password against a hash.
Parameters:
password(string) - Password to verifyhash(string) - Hash to verify againstsalt(string) - Salt used for hashing
Returns: Promise<boolean> - True if password matches
const isValid = await crypto.verifyHash('MyPassword123', storedHash, storedSalt);
Generate cryptographically secure random bytes.
Parameters:
length(number, default: 32) - Number of bytes to generate
Returns: string - Base64 encoded random bytes
const sessionToken = crypto.randomBytes(32);
const shortId = crypto.randomBytes(16);
Get information about the current runtime platform.
Returns: Object - Platform details
const info = crypto.getPlatformInfo();
// { platform: 'node', hasCrypto: true, version: '1.0.0' }
Server (Node.js):
const crypto = require('cross-crypto');
// Generate shared key during authentication
const sharedKey = await crypto.generateKey();
// Encrypt message before sending
const message = { text: 'Hello!', from: 'Alice', timestamp: Date.now() };
const encrypted = await crypto.encryptObject(message, sharedKey);
// Send encrypted to client
res.json(encrypted);
Client (React):
import crypto from 'cross-crypto';
// Receive encrypted message
const response = await fetch('/api/messages');
const encryptedMessage = await response.json();
// Decrypt message
const message = await crypto.decryptObject(encryptedMessage, sharedKey);
console.log(message.text); // 'Hello!'
// Registration
const password = 'UserPassword123';
const hashResult = await crypto.hash(password);
// Store in database
await db.users.create({
email: 'user@example.com',
passwordHash: hashResult.hash,
passwordSalt: hashResult.salt
});
// Login
const user = await db.users.findByEmail('user@example.com');
const isValid = await crypto.verifyHash(
inputPassword,
user.passwordHash,
user.passwordSalt
);
if (isValid) {
// Generate session token
const sessionToken = crypto.randomBytes(32);
// Login successful
}
// Encrypt sensitive data before storing
const sensitiveData = {
ssn: '123-45-6789',
creditCard: '4111-1111-1111-1111',
cvv: '123'
};
const encrypted = await crypto.encryptObject(sensitiveData, userKey);
await db.save({ userId: 123, data: encrypted });
// Decrypt when needed
const stored = await db.find({ userId: 123 });
const decrypted = await crypto.decryptObject(stored.data, userKey);
// Sender encrypts
const message = 'This is private';
const encrypted = await crypto.encrypt(message, recipientPublicKey);
// Send over network
await fetch('/api/messages', {
method: 'POST',
body: JSON.stringify(encrypted)
});
// Recipient decrypts
const response = await fetch('/api/messages/123');
const encrypted = await response.json();
const message = await crypto.decrypt(encrypted, myPrivateKey);
- AES-GCM encryption with 256-bit keys
- PBKDF2 password hashing with 100,000 iterations and SHA-256
- Cryptographically secure random number generation using
crypto.getRandomValues() - Unique IV (Initialization Vector) generated for each encryption operation
- Keys should be stored securely - never hardcode in source code
- Use HTTPS/TLS for transmitting encrypted data over networks
- Salt is automatically generated for each password hash
| Platform | Support | Implementation |
|---|---|---|
| Node.js 15+ | β Native | Built-in Web Crypto API |
| Modern Browsers | β Native | Chrome, Firefox, Safari, Edge |
| React Native | β Polyfill | Requires react-native-quick-crypto |
Browser Support:
- Chrome 37+
- Firefox 34+
- Safari 11+
- Edge 79+
Run tests
npm run example:node
Test Output: β generateKey() - Should generate encryption key β encrypt() - Should encrypt string β decrypt() - Should decrypt to original β encryptObject() - Should encrypt object β decryptObject() - Should decrypt object β hash() - Should hash password β verifyHash() - Should verify correct password β randomBytes() - Should generate random bytes
Check the examples/ directory for complete implementations:
node-example.js- Comprehensive Node.js usage with all methodsreact-example.jsx- React.js browser implementation with UIreact-native-example.jsx- React Native mobile implementation
Run examples:
node examples/node-example.js
Solution:
npm install react-native-quick-crypto
cd ios && pod install
Follow the setup guide.
Solution: Upgrade to Node.js 15 or later:
node --version # Should be >= 15.0.0
Solution: Ensure you're using HTTPS (required for Web Crypto API):
- Use
https://in production - Use
http://localhostfor development
Contributions are welcome! Please ensure:
- All tests pass:
npm test - Add tests for new features
- Follow existing code style
- Update documentation
This is free and unencumbered software released into the public domain. See UNLICENSE for details.
Anyone can use, modify, and distribute this software for any purpose without restriction.
- Issues: GitHub Issues
- Documentation: See examples and API reference above
- Questions: Open a GitHub discussion
- Same API everywhere - Write once, encrypt anywhere
- No platform-specific code - Package handles all differences automatically
- Production-ready - Built on standard Web Crypto API
- Well-documented - Extensive examples and comments
- Type-safe - Full TypeScript definitions included
| Feature | cross-crypto | crypto-js | node-forge |
|---|---|---|---|
| Node.js Support | β Native | β | β |
| Browser Support | β Native | β | β |
| React Native | β | β | β |
| Same API | β | β | β |
| Zero Dependencies* | β | β | β |
| Web Crypto API | β | β | β |
| TypeScript | β | β | β |
*Except React Native which requires react-native-quick-crypto
- Chat Applications - End-to-end encrypted messaging
- User Authentication - Secure password storage
- Data Storage - Encrypt sensitive database records
- API Communication - Secure client-server data exchange
- File Encryption - Protect user files
- Session Management - Generate secure tokens
- Initial release
- Support for Node.js, React.js, and React Native
- 8 core methods: encrypt, decrypt, encryptObject, decryptObject, hash, verifyHash, generateKey, randomBytes
- Comprehensive test suite
- Full documentation and examples
Made with β€οΈ for the JavaScript community
Package Name: cross-crypto
Author: Your Name
License: Unlicense (Public Domain)