Skip to content

Commit 97bf6c5

Browse files
committed
feat: add Cipher utility for AES-GCM encryption with Scrypt key derivation
- Implemented Cipher class for secure encryption and decryption. - Added methods for encrypting and decrypting text with support for AAD. - Introduced Scrypt parameters for key derivation. - Created types for EncryptedData and ScryptParams. - Added tests for various encryption scenarios, including handling of AAD and corrupted data. - Configured TypeScript and bundler settings for the project. - Included Prettier configuration for code formatting. - Established package.json with necessary metadata and scripts for development.
0 parents  commit 97bf6c5

File tree

13 files changed

+1149
-0
lines changed

13 files changed

+1149
-0
lines changed

.gitignore

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# dependencies (bun install)
2+
node_modules
3+
4+
# output
5+
out
6+
dist
7+
*.tgz
8+
9+
# code coverage
10+
coverage
11+
*.lcov
12+
13+
# logs
14+
logs
15+
_.log
16+
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
17+
18+
# dotenv environment variable files
19+
.env
20+
.env.*
21+
22+
# caches
23+
.eslintcache
24+
.cache
25+
*.tsbuildinfo
26+
27+
# IntelliJ based IDEs
28+
.idea
29+
30+
# Finder (MacOS) folder config
31+
.DS_Store

CHANGELOG.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Changelog
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+
## [1.0.1] - 2025-06-05
9+
10+
### Added
11+
- Initial release of cipher-utility library
12+
- `Cipher` class for secure encryption and decryption using AES-GCM
13+
- Support for AES-256-GCM, AES-192-GCM, and AES-128-GCM algorithms
14+
- Scrypt key derivation with configurable parameters (N, r, p)
15+
- Random salt and IV generation for each encryption operation
16+
- Additional Authenticated Data (AAD) support
17+
- Secure memory cleanup to prevent key material leakage
18+
- Support for base64 and hex encodings
19+
- Comprehensive TypeScript type definitions
20+
- Complete test suite with 100+ test cases
21+
- MIT license
22+
- Full documentation and examples
23+
24+
### Security Features
25+
- AES-GCM encryption providing both confidentiality and authenticity
26+
- Scrypt key derivation for protection against brute-force attacks
27+
- Cryptographically secure random number generation for salts and IVs
28+
- Authentication tag verification to detect tampering
29+
- Secure buffer zeroing to prevent memory leakage
30+
31+
[1.0.1]: https://github.com/liorcodev/cipher-utility/releases/tag/v1.0.1

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2025 Lior Cohen
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# cipher-utility
2+
3+
[![MIT License](https://img.shields.io/badge/License-MIT-blue.svg)](https://choosealicense.com/licenses/mit/)
4+
5+
A utility library for robust and secure cryptographic operations using Node.js `crypto` module. It provides easy-to-use methods for encrypting and decrypting text with AES-GCM, leveraging Scrypt for key derivation.
6+
7+
## Features
8+
9+
* **Strong Encryption**: Uses AES-GCM ( Galois/Counter Mode) which provides both confidentiality and authenticity. Supports `aes-256-gcm`, `aes-192-gcm`, and `aes-128-gcm`.
10+
* **Secure Key Derivation**: Employs `scryptSync` for deriving encryption keys from passwords, offering protection against brute-force attacks.
11+
* **Random Salt & IV**: Automatically generates a unique salt and initialization vector (IV) for each encryption operation, enhancing security.
12+
* **Additional Authenticated Data (AAD)**: Supports AAD to ensure the integrity of non-confidential data alongside the encrypted payload.
13+
* **Customizable Parameters**: Allows configuration of Scrypt parameters (`N`, `r`, `p`) for fine-tuning security vs. performance.
14+
* **Flexible Encodings**: Supports `base64` and `hex` encodings for encrypted data, IV, tag, and salt.
15+
* **Type-Safe**: Written in TypeScript with comprehensive type definitions.
16+
* **Error Handling**: Gracefully handles decryption failures (e.g., wrong password, corrupted data) by returning `null`.
17+
18+
## Installation
19+
20+
```bash
21+
npm install cipher-utility
22+
# or
23+
yarn add cipher-utility
24+
# or
25+
bun add cipher-utility
26+
```
27+
28+
## Usage
29+
30+
```typescript
31+
import { Cipher } from 'cipher-utility';
32+
33+
const cipher = new Cipher();
34+
35+
const text = 'This is a secret message!';
36+
const password = 'super-strong-password123';
37+
38+
// Encrypt
39+
const encrypted = cipher.encrypt(text, password);
40+
41+
// Decrypt
42+
const decrypted = cipher.decrypt(encrypted, password);
43+
44+
console.log('Decrypted:', decrypted); // Output: This is a secret message!
45+
```
46+
47+
## API
48+
49+
### `new Cipher(params?: ScryptParams)`
50+
51+
Creates a new `Cipher` instance.
52+
53+
* `params` (optional): An object to customize Scrypt parameters.
54+
* `N`: CPU/memory cost parameter (default: `4096`).
55+
* `r`: Block size (default: `8`).
56+
* `p`: Parallelization parameter (default: `1`).
57+
58+
**Note**: The key length is automatically determined based on the algorithm used (16 bytes for AES-128, 24 bytes for AES-192, 32 bytes for AES-256).
59+
60+
### `cipher.encrypt(text, password, algorithm?, encoding?, aad?)`
61+
62+
Encrypts the input text.
63+
64+
* `text: string`: The plaintext to encrypt.
65+
* `password: string`: The password to derive the encryption key.
66+
* `algorithm?: CipherGCMTypes`: The AES-GCM algorithm to use (default: `'aes-256-gcm'`).
67+
Supported: `'aes-256-gcm'`, `'aes-192-gcm'`, `'aes-128-gcm'`.
68+
* `encoding?: Encoding`: The encoding for the output strings (encrypted, iv, tag, salt) (default: `'base64'`).
69+
Supported: `'base64'`, `'hex'`.
70+
* `aad?: string`: Optional Additional Authenticated Data.
71+
* **Returns**: `EncryptedData` object:
72+
```typescript
73+
type EncryptedData = {
74+
encrypted: string; // The encrypted text
75+
iv: string; // The initialization vector
76+
tag: string; // The authentication tag
77+
salt: string; // The salt used for key derivation
78+
aad?: string; // The AAD, if provided
79+
};
80+
```
81+
82+
### `cipher.decrypt(encryptedData, password, algorithm?, encoding?)`
83+
84+
Decrypts the encrypted data.
85+
86+
* `encryptedData: EncryptedData`: The object returned by the `encrypt` method.
87+
* `password: string`: The password used for encryption.
88+
* `algorithm?: CipherGCMTypes`: The AES-GCM algorithm used for encryption (default: `'aes-256-gcm'`).
89+
* `encoding?: Encoding`: The encoding used for the input strings in `encryptedData` (default: `'base64'`).
90+
* **Returns**: `string | null`: The decrypted plaintext, or `null` if decryption fails (e.g., wrong password, tampered data, incorrect AAD).
91+
92+
## Development
93+
94+
### Prerequisites
95+
96+
* Node.js (LTS recommended)
97+
* Bun (for running scripts, optional if you prefer npm/yarn)
98+
99+
### Setup
100+
101+
1. Clone the repository:
102+
```bash
103+
git clone https://github.com/liorcodev/cipher-utility.git
104+
cd cipher-utility
105+
```
106+
2. Install dependencies:
107+
```bash
108+
bun install
109+
# or
110+
npm install
111+
```
112+
113+
### Scripts
114+
115+
* `bun run format`: Format code using Prettier.
116+
* `bun run dev`: Run `index.ts` in watch mode (useful for quick testing).
117+
* `bun run build`: Build the library using `tsup`. Output is in the `dist` folder.
118+
* `bun test`: Run tests using Bun's test runner (tests are in `src/cipher.test.ts`).
119+
120+
## Contributing
121+
122+
Contributions are welcome! Please feel free to submit a Pull Request.
123+
124+
1. Fork the Project
125+
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
126+
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
127+
4. Push to the Branch (`git push origin feature/AmazingFeature`)
128+
5. Open a Pull Request
129+
130+
## License
131+
132+
Distributed under the MIT License. See `LICENSE` file for more information.
133+
134+
---

0 commit comments

Comments
 (0)