UNPKG

dcoderz-encryption

Version:

Cross-platform encryption library with JavaScript and Python compatibility. Features custom cipher algorithms with character substitution, matrix transformations, and integrity verification.

620 lines (476 loc) โ€ข 17.2 kB
# Dcoderz Encryption Javascript ๐Ÿ”’ A cross-platform encryption library with JavaScript and Python compatibility. Features custom cipher algorithms with character substitution, matrix transformations, and integrity verification. [![npm version](https://badge.fury.io/js/dcoderz-encryption.svg)](https://www.npmjs.com/package/dcoderz-encryption) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Node.js Version](https://img.shields.io/node/v/dcoderz-encryption.svg)](https://nodejs.org/en/download/) ## โœจ Features - ๐Ÿ” **Proprietary Encryption Algorithm** - Multi-layered security with 6 transformation steps - ๐ŸŒ **Cross-Platform Compatible** - Works identically with Python implementation - ๐Ÿ›ก๏ธ **Integrity Verification** - Built-in checksums detect tampering - ๐ŸŽฏ **Deterministic** - Same input always produces same output - ๐Ÿš€ **High Performance** - Optimized for speed and memory usage - ๐Ÿ“ฆ **Zero Dependencies** - No external dependencies required - ๐Ÿ”ง **CLI Tool** - Command-line interface included - ๐Ÿ“š **TypeScript Support** - Full TypeScript definitions included ## ๐Ÿš€ Installation ```bash npm install dcoderz-encryption ``` ## ๐Ÿ“– Quick Start ```javascript const { encrypt, decrypt, generateKey } = require('dcoderz-encryption'); // Basic encryption/decryption const plaintext = 'Hello, World!'; const key = 'my-secret-key'; const encrypted = encrypt(plaintext, key); console.log('Encrypted:', encrypted); const decrypted = decrypt(encrypted, key); console.log('Decrypted:', decrypted); // Generate a random key const randomKey = generateKey(); console.log('Generated key:', randomKey); ``` ## ๐Ÿ”ง API Reference ### Functions #### `encrypt(plaintext, key)` Encrypts plaintext using the specified key. **Parameters:** - `plaintext` (string) - The text to encrypt - `key` (string) - The encryption key **Returns:** `string` - The encrypted text **Example:** ```javascript const encrypted = encrypt('Hello World!', 'my-key'); ``` #### `decrypt(ciphertext, key)` Decrypts ciphertext using the specified key. **Parameters:** - `ciphertext` (string) - The encrypted text to decrypt - `key` (string) - The decryption key **Returns:** `string` - The decrypted text **Example:** ```javascript const decrypted = decrypt(encrypted, 'my-key'); ``` #### `generateKey(length)` Generates a random encryption key. **Parameters:** - `length` (number, optional) - Key length (default: 32) **Returns:** `string` - A random key **Example:** ```javascript const key = generateKey(16); // 16-character key ``` #### `isValidCiphertext(ciphertext)` Validates if a string is properly formatted encrypted text. **Parameters:** - `ciphertext` (string) - The text to validate **Returns:** `boolean` - True if valid, false otherwise **Example:** ```javascript const isValid = isValidCiphertext(encrypted); ``` ### Classes #### `CipherEngine` Advanced encryption engine for reusable instances. **Constructor:** ```javascript const cipher = new CipherEngine('my-key'); ``` **Methods:** - `encrypt(plaintext)` - Encrypt text - `decrypt(ciphertext)` - Decrypt text **Example:** ```javascript const cipher = new CipherEngine('my-key'); const encrypted = cipher.encrypt('Hello World!'); const decrypted = cipher.decrypt(encrypted); ``` ## ๐Ÿ–ฅ๏ธ CLI Usage The library includes a command-line interface: ```bash # Interactive mode npx dcoderz-encrypt # Direct commands npx dcoderz-encrypt encrypt "Hello World!" "my-key" npx dcoderz-encrypt decrypt "encrypted-text" "my-key" npx dcoderz-encrypt generate-key 32 npx dcoderz-encrypt test ``` ## ๐ŸŒ Cross-Platform Compatibility This library is fully compatible with the Python implementation. You can encrypt data in JavaScript and decrypt it in Python, or vice versa. ### JavaScript Example: ```javascript const { encrypt } = require('dcoderz-encryption'); const encrypted = encrypt('Hello World!', 'test123'); console.log(encrypted); // 's[f|0+o)5KW[lKafq(B0f%MBC ``` ### Python Example: ```python from dcoderz_encryption import decrypt decrypted = decrypt("'s[f|0+o)5KW[lKafq(B0f%MBC", "test123") print(decrypted) # Hello World! ``` ## ๐Ÿ”’ Security Features The encryption algorithm combines multiple security layers: 1. **Character Substitution** - Dynamic cipher wheel based on key 2. **Matrix Transformation** - Row/column scrambling 3. **Position-based XOR** - Key-dependent bit manipulation 4. **Position Scrambling** - Deterministic character reordering 5. **Integrity Checksum** - MD5 hash for tampering detection 6. **Custom Encoding** - Base-94 encoding for safe transport ## ๐Ÿงช Testing Run the test suite: ```bash npm test ``` Run examples: ```bash npm run example ``` ## ๐Ÿ“š TypeScript Support The library includes full TypeScript definitions with complete type safety: ```typescript import { encrypt, decrypt, CipherEngine, generateKey } from 'dcoderz-encryption'; // All functions are fully typed const plaintext: string = 'Hello World!'; const key: string = 'my-secret-key'; const encrypted: string = encrypt(plaintext, key); const decrypted: string = decrypt(encrypted, key); // CipherEngine class with full typing const cipher: CipherEngine = new CipherEngine('my-key'); const result: string = cipher.encrypt('TypeScript message'); // Key generation with optional length parameter const randomKey: string = generateKey(32); const shortKey: string = generateKey(16); // Type-safe error handling try { const result = decrypt('invalid-data', 'wrong-key'); } catch (error: unknown) { if (error instanceof Error) { console.log('Decryption failed:', error.message); } } ``` ### Advanced TypeScript Features Create strongly-typed wrappers for object encryption: ```typescript import { CipherEngine } from 'dcoderz-encryption'; // Create a strongly-typed wrapper class TypedCipherEngine<T> extends CipherEngine { encryptObject(obj: T): string { return this.encrypt(JSON.stringify(obj)); } decryptObject(ciphertext: string): T { const decrypted = this.decrypt(ciphertext); return JSON.parse(decrypted) as T; } } // Usage with type safety interface UserData { id: number; name: string; email: string; } const cipher = new TypedCipherEngine<UserData>('user-key'); const userData: UserData = { id: 1, name: 'John', email: 'john@example.com' }; const encrypted = cipher.encryptObject(userData); const decrypted: UserData = cipher.decryptObject(encrypted); ``` ## โš›๏ธ React/JSX Support Perfect for React applications with full component examples: ### Basic React Component ```jsx import React, { useState } from 'react'; import { encrypt, decrypt, generateKey } from 'dcoderz-encryption'; function EncryptionComponent() { const [message, setMessage] = useState(''); const [key, setKey] = useState(''); const [encrypted, setEncrypted] = useState(''); const [decrypted, setDecrypted] = useState(''); const handleEncrypt = () => { try { const result = encrypt(message, key); setEncrypted(result); } catch (error) { alert(`Encryption failed: ${error.message}`); } }; const handleDecrypt = () => { try { const result = decrypt(encrypted, key); setDecrypted(result); } catch (error) { alert(`Decryption failed: ${error.message}`); } }; const handleGenerateKey = () => { const newKey = generateKey(); setKey(newKey); }; return ( <div className="encryption-tool"> <h2>๐Ÿ”’ Dcoderz Encryption Tool</h2> <div className="form-group"> <label>Message:</label> <textarea value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Enter message to encrypt" /> </div> <div className="form-group"> <label>Key:</label> <input type="text" value={key} onChange={(e) => setKey(e.target.value)} placeholder="Enter encryption key" /> <button onClick={handleGenerateKey}>Generate Random Key</button> </div> <div className="buttons"> <button onClick={handleEncrypt} disabled={!message || !key}> Encrypt </button> <button onClick={handleDecrypt} disabled={!encrypted || !key}> Decrypt </button> </div> {encrypted && ( <div className="result"> <label>Encrypted:</label> <textarea value={encrypted} readOnly /> </div> )} {decrypted && ( <div className="result"> <label>Decrypted:</label> <textarea value={decrypted} readOnly /> </div> )} </div> ); } export default EncryptionComponent; ``` ### React Hook for Encryption ```jsx import { useState, useCallback } from 'react'; import { encrypt, decrypt, CipherEngine } from 'dcoderz-encryption'; export function useEncryption(persistentKey) { const [cipher] = useState(() => persistentKey ? new CipherEngine(persistentKey) : null ); const encryptText = useCallback((text, key) => { try { return cipher ? cipher.encrypt(text) : encrypt(text, key); } catch (error) { throw new Error(`Encryption failed: ${error.message}`); } }, [cipher]); const decryptText = useCallback((ciphertext, key) => { try { return cipher ? cipher.decrypt(ciphertext) : decrypt(ciphertext, key); } catch (error) { throw new Error(`Decryption failed: ${error.message}`); } }, [cipher]); return { encryptText, decryptText }; } // Usage in component: function MyComponent() { const { encryptText, decryptText } = useEncryption('my-app-key'); const handleSaveData = (data) => { const encrypted = encryptText(JSON.stringify(data)); localStorage.setItem('userData', encrypted); }; const handleLoadData = () => { const encrypted = localStorage.getItem('userData'); if (encrypted) { const decrypted = decryptText(encrypted); return JSON.parse(decrypted); } }; // ... rest of component } ``` ### TypeScript + React ```tsx import React, { useState, FC } from 'react'; import { encrypt, decrypt, generateKey } from 'dcoderz-encryption'; interface EncryptionFormProps { onEncrypted?: (encrypted: string) => void; onDecrypted?: (decrypted: string) => void; } const EncryptionForm: FC<EncryptionFormProps> = ({ onEncrypted, onDecrypted }) => { const [message, setMessage] = useState<string>(''); const [key, setKey] = useState<string>(''); const [loading, setLoading] = useState<boolean>(false); const handleEncrypt = async (): Promise<void> => { setLoading(true); try { const encrypted: string = encrypt(message, key); onEncrypted?.(encrypted); } catch (error) { console.error('Encryption error:', error); } finally { setLoading(false); } }; const handleGenerateKey = (): void => { const newKey: string = generateKey(32); setKey(newKey); }; return ( <form onSubmit={(e) => { e.preventDefault(); handleEncrypt(); }}> <input type="text" value={message} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMessage(e.target.value)} placeholder="Enter message" /> <input type="text" value={key} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setKey(e.target.value)} placeholder="Enter key" /> <button type="button" onClick={handleGenerateKey}> Generate Key </button> <button type="submit" disabled={loading || !message || !key}> {loading ? 'Encrypting...' : 'Encrypt'} </button> </form> ); }; export default EncryptionForm; ``` ### Next.js Usage Perfect for Next.js applications: ```jsx // pages/encryption.js import { useState } from 'react'; import { encrypt, decrypt, generateKey } from 'dcoderz-encryption'; export default function EncryptionPage() { const [result, setResult] = useState(''); const handleEncrypt = () => { const encrypted = encrypt('Hello Next.js!', 'next-key'); setResult(encrypted); }; return ( <div> <h1>Encryption in Next.js</h1> <button onClick={handleEncrypt}>Encrypt</button> {result && <p>Encrypted: {result}</p>} </div> ); } ``` ## ๐Ÿ› ๏ธ Framework Compatibility - โœ… **TypeScript**: Full type definitions included - โœ… **React/JSX**: Works perfectly in React components - โœ… **Next.js**: Compatible with SSR and client-side - โœ… **Vue.js**: Works in Vue applications - โœ… **Angular**: Compatible with Angular projects - โœ… **Node.js**: Server-side usage - โœ… **Browser**: Client-side usage - โœ… **Webpack**: Module bundler compatible - โœ… **Vite**: Modern build tool compatible ## ๐Ÿ“‹ Examples ### Basic Usage ```javascript const { encrypt, decrypt } = require('dcoderz-encryption'); const message = 'Secret message'; const key = 'my-secret-key'; const encrypted = encrypt(message, key); const decrypted = decrypt(encrypted, key); console.log(message === decrypted); // true ``` ### Using CipherEngine Class ```javascript const { CipherEngine } = require('dcoderz-encryption'); const cipher = new CipherEngine('persistent-key'); // Encrypt multiple messages with same key const msg1 = cipher.encrypt('First message'); const msg2 = cipher.encrypt('Second message'); // Decrypt them back console.log(cipher.decrypt(msg1)); // First message console.log(cipher.decrypt(msg2)); // Second message ``` ### Error Handling ```javascript const { encrypt, decrypt } = require('dcoderz-encryption'); try { const encrypted = encrypt('Hello', 'key'); const decrypted = decrypt(encrypted, 'wrong-key'); } catch (error) { console.log('Decryption failed:', error.message); } ``` ### JSON Data Encryption ```javascript const { encrypt, decrypt } = require('dcoderz-encryption'); const data = { user: 'john', age: 30, active: true }; const jsonString = JSON.stringify(data); const encrypted = encrypt(jsonString, 'json-key'); const decrypted = decrypt(encrypted, 'json-key'); const parsedData = JSON.parse(decrypted); console.log(parsedData); // { user: 'john', age: 30, active: true } ``` ## ๐ŸŽฏ Performance - **Encryption Speed**: ~1MB/s on typical hardware - **Memory Usage**: Minimal overhead - **Key Generation**: Cryptographically secure random keys - **Deterministic**: Same input always produces same output ## ๐Ÿ›ก๏ธ Security Considerations - **Key Management**: Store keys securely, never hardcode in production - **Key Strength**: Use strong, unique keys for each application - **Transport Security**: Use HTTPS for transmitting encrypted data - **Key Rotation**: Regularly rotate encryption keys - **Backup**: Securely backup keys to prevent data loss ## ๐Ÿ“ฆ Package Contents ``` dcoderz-encryption/ โ”œโ”€โ”€ lib/ โ”‚ โ””โ”€โ”€ index.js # Main library โ”œโ”€โ”€ bin/ โ”‚ โ””โ”€โ”€ cli.js # Command-line interface โ”œโ”€โ”€ types/ โ”‚ โ””โ”€โ”€ index.d.ts # TypeScript definitions โ”œโ”€โ”€ test/ โ”‚ โ””โ”€โ”€ test.js # Test suite โ”œโ”€โ”€ examples/ โ”‚ โ””โ”€โ”€ basic-usage.js # Usage examples โ”œโ”€โ”€ README.md # This file โ””โ”€โ”€ package.json # Package configuration ``` ## ๐Ÿ”„ Changelog ### v1.0.0 - Initial release - Cross-platform compatibility with Python - CLI tool - TypeScript support - Comprehensive test suite ## ๐Ÿค Contributing Contributions are welcome! Please feel free to submit a Pull Request. 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests if applicable 5. Submit a pull request ## ๐Ÿ“„ License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## ๐Ÿข About Dcoderz Dcoderz is a software development company specializing in security solutions and cross-platform applications. - Website: https://www.facebook.com/dcoderzphilippines - Email: m4kuguren@gmail.com ## ๐Ÿ†˜ Support If you encounter any issues or have questions: 1. Check the [Issues](https://github.com/makuguren/Dcoderz-Encryption-Javascript/issues) page 2. Create a new issue with detailed information 3. Contact us at m4kuguren@gmail.com ## ๐Ÿ™ Acknowledgments - Thanks to the cryptography community for inspiration - Special thanks to all contributors and testers