Skip to content

tkdonda-dev/cross-crypto

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Cross Crypto

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.

✨ Features

  • 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

πŸ“¦ Installation

npm install cross-crypto

React Native Setup

React Native requires an additional polyfill:

npm install react-native-quick-crypto

Follow the react-native-quick-crypto setup guide for platform-specific configuration.

πŸš€ Quick Start

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();

πŸ“š API Reference

generateKey()

Generate a cryptographically secure AES-256 encryption key.

Returns: Promise<string> - Base64 encoded key

const key = await crypto.generateKey();
// Store this key securely!

encrypt(plaintext, key)

Encrypt a string using AES-GCM.

Parameters:

  • plaintext (string) - Text to encrypt
  • key (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(encryptedData, key)

Decrypt encrypted data.

Parameters:

  • encryptedData (Object) - Object returned from encrypt()
  • key (string) - Base64 encoded decryption key (same as encryption)

Returns: Promise<string> - Decrypted plaintext

const decrypted = await crypto.decrypt(encrypted, key);

encryptObject(obj, key)

Encrypt a JavaScript object (automatically converts to JSON).

Parameters:

  • obj (Object) - Object to encrypt
  • key (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);

decryptObject(encryptedData, key)

Decrypt and parse a JavaScript object.

Parameters:

  • encryptedData (Object) - Encrypted object data
  • key (string) - Base64 encoded decryption key

Returns: Promise<Object> - Decrypted object

const decrypted = await crypto.decryptObject(encrypted, key);

hash(password, salt?)

Hash a password using PBKDF2 with 100,000 iterations.

Parameters:

  • password (string) - Password to hash
  • salt (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

verifyHash(password, hash, salt)

Verify a password against a hash.

Parameters:

  • password (string) - Password to verify
  • hash (string) - Hash to verify against
  • salt (string) - Salt used for hashing

Returns: Promise<boolean> - True if password matches

const isValid = await crypto.verifyHash('MyPassword123', storedHash, storedSalt);

randomBytes(length)

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);

getPlatformInfo()

Get information about the current runtime platform.

Returns: Object - Platform details

const info = crypto.getPlatformInfo();
// { platform: 'node', hasCrypto: true, version: '1.0.0' }

πŸ’‘ Usage Examples

Chat Application (Node.js + React)

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!'

User Authentication

// 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
}

Secure Data Storage

// 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);

End-to-End Encrypted Messages

// 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);

πŸ” Security Notes

  • 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 Compatibility

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+

πŸ§ͺ Testing

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


πŸ“ Examples

Check the examples/ directory for complete implementations:

  • node-example.js - Comprehensive Node.js usage with all methods
  • react-example.jsx - React.js browser implementation with UI
  • react-native-example.jsx - React Native mobile implementation

Run examples:

node examples/node-example.js

πŸ”§ Troubleshooting

React Native - "react-native-quick-crypto not installed"

Solution:

npm install react-native-quick-crypto
cd ios && pod install

Follow the setup guide.


Node.js - "Web Crypto API not available"

Solution: Upgrade to Node.js 15 or later:

node --version # Should be >= 15.0.0

Browser - "Web Crypto API not available"

Solution: Ensure you're using HTTPS (required for Web Crypto API):

  • Use https:// in production
  • Use http://localhost for development

🀝 Contributing

Contributions are welcome! Please ensure:

  1. All tests pass: npm test
  2. Add tests for new features
  3. Follow existing code style
  4. Update documentation

πŸ“„ License

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.


πŸ†˜ Support

  • Issues: GitHub Issues
  • Documentation: See examples and API reference above
  • Questions: Open a GitHub discussion

πŸ”‘ Key Points

  1. Same API everywhere - Write once, encrypt anywhere
  2. No platform-specific code - Package handles all differences automatically
  3. Production-ready - Built on standard Web Crypto API
  4. Well-documented - Extensive examples and comments
  5. Type-safe - Full TypeScript definitions included

πŸ“Š Comparison

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


🎯 Use Cases

  • 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

πŸ“ Changelog

v1.0.0

  • 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)

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors