Package Exports
- nestjs-crypto
- nestjs-crypto/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (nestjs-crypto) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
NestJS Crypto
A comprehensive crypto module for NestJS applications, providing both irreversible (bcrypt) and reversible (AES) encryption methods with automatic secret generation, performance benchmarks, and extensive documentation.
Features
- ๐ Dual Encryption Support: Bcrypt for password hashing and AES for data encryption/decryption
- โก High Performance: Optimized AES encryption with benchmark comparisons
- ๐ Automatic Secret Generation: Secure random key and IV generation
- ๐ก๏ธ Security First: Industry-standard encryption algorithms with configurable options
- ๐ Full Documentation: VitePress docs with API references and examples
- ๐ง TypeScript Native: Strict typing and full IntelliSense support
- ๐งช Benchmarks: Built-in performance testing tools
- ๐ NestJS Integration: Seamless module integration with async configuration support
Installation
npm install nestjs-cryptoPeer Dependencies
npm install @nestjs/common @nestjs/core bcrypt reflect-metadata typescriptQuick Start
Basic Setup
import { Module } from '@nestjs/common';
import { CryptoModule } from 'nestjs-crypto';
@Module({
imports: [
CryptoModule.forRoot({
useBcrypt: true,
bcryptSaltRounds: 12,
useAes: true,
}),
],
})
export class AppModule {}Using the Services
import { Injectable } from '@nestjs/common';
import { BcryptService, AesService } from 'nestjs-crypto';
@Injectable()
export class AuthService {
constructor(
private readonly bcryptService: BcryptService,
private readonly aesService: AesService,
) {}
async hashPassword(password: string): Promise<string> {
return this.bcryptService.hash(password, 12);
}
async verifyPassword(password: string, hash: string): Promise<boolean> {
return this.bcryptService.compare(password, hash);
}
encryptData(data: string): { encrypted: string; key: string; iv: string } {
return this.aesService.encrypt(data);
}
decryptData(encrypted: string, key: string, iv: string): string {
return this.aesService.decrypt(encrypted, key, iv);
}
}Configuration Options
Module Options
interface CryptoModuleOptions {
isGlobal?: boolean; // Make services globally available
secret?: string; // Custom secret (auto-generated if not provided)
showSecret?: boolean; // Log generated secrets (development only)
useBcrypt?: boolean; // Enable bcrypt service (default: true)
bcryptSaltRounds?: number; // Salt rounds for bcrypt (default: 10)
useAes?: boolean; // Enable AES service (default: true)
aesKey?: string; // Custom AES key (auto-generated if not provided)
aesIv?: string; // Custom AES IV (auto-generated if not provided)
debug?: boolean; // Enable debug logging
}Async Configuration
For dynamic configuration from external sources:
import { CryptoModule } from 'nestjs-crypto';
@Module({
imports: [
CryptoModule.forRootAsync({
useFactory: async (configService: ConfigService) => ({
secret: configService.get('CRYPTO_SECRET'),
bcryptSaltRounds: configService.get('BCRYPT_ROUNDS', 12),
useAes: configService.get('USE_AES', true),
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}API Reference
BcryptService
hash(data: string, saltRounds: number): Promise<string>hashSync(data: string, saltRounds: number): stringcompare(data: string, encrypted: string): Promise<boolean>compareSync(data: string, encrypted: string): booleangenSalt(saltRounds: number): Promise<string>getSaltRounds(encrypted: string): number
AesService
encrypt(data: string, key?, iv?): { encrypted: string; key: string; iv: string }decrypt(encrypted: string, key: string, iv: string): stringencryptSync(data: string, key?, iv?): { encrypted: string; key: string; iv: string }decryptSync(encrypted: string, key: string, iv: string): stringgenerateKey(): BuffergenerateIv(): Buffer
Utility Functions
generateAesKey(length?: number): stringgenerateAesIv(length?: number): stringgenerateSecret(length?: number): string
Performance Benchmarks
Run performance benchmarks:
npm run benchmarkExample output:
Benchmarking Bcrypt...
Bcrypt hash (100 iterations): 3577ms
Bcrypt compare (100 iterations): 3514ms
Benchmarking AES...
AES encrypt (1000 iterations): 9ms
AES decrypt (1000 iterations): 4msDocumentation
- ๐ Full Documentation
- ๐ API Reference
Development
Prerequisites
- Node.js 18+
- npm or yarn
Setup
git clone https://github.com/cstrp/nestjs-crypto.git
cd nestjs-crypto
npm installAvailable Scripts
npm run build # Build the library
npm run lint # Run ESLint
npm run benchmark # Run performance benchmarks
npm run docs:dev # Start documentation server
npm run docs:build # Build documentation
npm run typedoc:build # Build API documentationTesting
The library includes comprehensive unit tests with high code coverage:
npm test # Run tests
npm run test:watch # Run tests in watch mode
npm run test:cov # Run tests with coverage reportCurrent Test Coverage:
- โ 31 test cases passing
- ๐ 67%+ service coverage
- ๐ก๏ธ 91%+ error handling coverage
- โ๏ธ 79%+ validation coverage
Test files are located in lib/**/__tests__/ directories:
bcrypt.service.spec.ts- BcryptService testsaes.service.spec.ts- AesService tests
Security Considerations
- Bcrypt: Use for password hashing only. Higher salt rounds increase security but impact performance.
- AES: Keep keys and IVs secure. Never hardcode them in source code.
- Secrets: The library generates secure random secrets, but consider using environment variables for production.
- Key Management: Rotate encryption keys periodically and implement proper key lifecycle management.
Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature - Commit changes:
git commit -m 'Add some feature' - Push to the branch:
git push origin feature/your-feature - Open a Pull Request
Development Guidelines
- Follow the existing code style (Prettier + ESLint)
- Add tests for new features
- Update documentation
- Run benchmarks to ensure performance
- Use conventional commits
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- ๐ง Email: cstrp@pm.me
- ๐ Issues: GitHub Issues
- ๐ฌ Discussions: GitHub Discussions
Changelog
See CHANGELOG.md for version history.
Made with โค๏ธ for the NestJS community