npm package: @merncloud/secure-crypto-utils
Description: A secure AES-256-CBC encryption/decryption utility with robust error handling and validation
Author: Anurag Jaisingh
Latest version: 1.0.2

# @merncloud/secure-crypto-utils

A secure, TypeScript-first encryption library using AES-256-CBC with robust error handling and validation.

## Features

- 🔒 **Secure**: Uses AES-256-CBC encryption with random IVs
- 🛡️ **Robust**: Comprehensive input validation and error handling
- 📝 **TypeScript**: Full TypeScript support with detailed type definitions
- 🧪 **Well-tested**: High test coverage with comprehensive test suite
- 🚀 **Easy to use**: Simple API with sensible defaults
- ⚡ **Performance**: Optimized for both security and speed

## Installation

```bash
npm install @merncloud/secure-crypto-utils
```

## Quick Start

```typescript
import { encrypt, decrypt } from "@merncloud/secure-crypto-utils";

// Set your encryption key (do this once, preferably via environment variable)
process.env.AES_SECRET_KEY = "your-32-character-secret-key-here!!!";

// Encrypt some data
const result = encrypt("Hello, World!");
console.log(result);
// {
//   encryptedData: 'base64-encoded-encrypted-data',
//   iv: 'base64-encoded-initialization-vector'
// }

// Decrypt the data
const decrypted = decrypt(result.encryptedData, result.iv);
console.log(decrypted); // 'Hello, World!'
```

## API Reference

### `encrypt(text: string, config?: CryptoConfig): EncryptionResult`

Encrypts text using AES-256-CBC encryption.

**Parameters:**

- `text`: The string to encrypt (max 10,000 characters by default)
- `config`: Optional configuration object

**Returns:** `EncryptionResult`

- `encryptedData`: Base64 encoded encrypted data
- `iv`: Base64 encoded initialization vector

**Example:**

```typescript
const result = encrypt("Sensitive data");

// With custom configuration
const result2 = encrypt("Data", {
  maxTextLength: 5000,
  encryptionKey: "custom-32-char-key-here-!!!!!!!!!",
});
```

### `decrypt(encryptedData: string, iv: string, config?: CryptoConfig): string`

Decrypts data that was encrypted with the `encrypt` function.

**Parameters:**

- `encryptedData`: Base64 encoded encrypted data
- `iv`: Base64 encoded initialization vector
- `config`: Optional configuration object

**Returns:** The decrypted string

**Example:**

```typescript
const decrypted = decrypt(result.encryptedData, result.iv);

// With custom key
const decrypted2 = decrypt(data, iv, {
  encryptionKey: "same-custom-key-used-for-encryption!",
});
```

### `generateKey(length?: number): string`

Generates a cryptographically secure random key.

**Parameters:**

- `length`: Key length in bytes (default: 32 for AES-256)

**Returns:** Base64 encoded random key

**Example:**

```typescript
const key = generateKey(); // 32-byte key
const longerKey = generateKey(64); // 64-byte key

// Use the generated key
process.env.AES_SECRET_KEY = key;
```

### `safeCompare(a: string, b: string): boolean`

Performs timing-safe string comparison to prevent timing attacks.

**Parameters:**

- `a`: First string to compare
- `b`: Second string to compare

**Returns:** `true` if strings are equal, `false` otherwise

**Example:**

```typescript
const isValid = safeCompare(userInput, expectedValue);
```

## Configuration

### Environment Variables

- `AES_SECRET_KEY`: Your encryption key (must be at least 32 characters)

### CryptoConfig Interface

```typescript
interface CryptoConfig {
  maxTextLength?: number; // Maximum text length (default: 10000)
  encryptionKey?: string; // Custom encryption key
  algorithm?: string; // Encryption algorithm (default: 'aes-256-cbc')
}
```

## Error Handling

The library provides specific error types for different failure scenarios:

```typescript
import {
  encrypt,
  ValidationError,
  DecryptionError,
  CryptoError,
} from "@merncloud/secure-crypto-utils";

try {
  const result = encrypt("data");
  const decrypted = decrypt(result.encryptedData, result.iv);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error("Invalid input:", error.message);
  } else if (error instanceof DecryptionError) {
    console.error("Decryption failed:", error.message);
  } else if (error instanceof CryptoError) {
    console.error("Crypto operation failed:", error.message);
  }
}
```

## Security Best Practices

1. **Key Management**: Never hardcode encryption keys. Use environment variables or secure key management services.

2. **Key Rotation**: Regularly rotate your encryption keys, especially in production environments.

3. **Input Validation**: The library validates inputs, but always validate data at your application level too.

4. **HTTPS**: Always use HTTPS when transmitting encrypted data over networks.

5. **Storage**: When storing encrypted data, store the IV alongside but never store the encryption key with the data.

## Advanced Usage

### Working with JSON Data

```typescript
const userData = { id: 123, email: "user@example.com", role: "admin" };
const jsonString = JSON.stringify(userData);

const encrypted = encrypt(jsonString);
const decrypted = decrypt(encrypted.encryptedData, encrypted.iv);
const parsedData = JSON.parse(decrypted);
```

### Database Integration

```typescript
// Storing in database
const sensitiveData = "user-sensitive-information";
const encrypted = encrypt(sensitiveData);

await db.users.update(userId, {
  encryptedData: encrypted.encryptedData,
  iv: encrypted.iv,
});

// Retrieving from database
const user = await db.users.findById(userId);
const decryptedData = decrypt(user.encryptedData, user.iv);
```

### Custom Key per Operation

```typescript
// Generate a unique key for specific data
const dataKey = generateKey();

const encrypted = encrypt("sensitive-data", { encryptionKey: dataKey });
const decrypted = decrypt(encrypted.encryptedData, encrypted.iv, {
  encryptionKey: dataKey,
});
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Run tests (`npm test`)
4. Commit your changes (`git commit -m 'Add amazing feature'`)
5. Push to the branch (`git push origin feature/amazing-feature`)
6. Open a Pull Request

## Testing

```bash
# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage
```

## License

MIT License - see the [LICENSE](LICENSE) file for details.

## Security

If you discover a security vulnerability, please send an email to anukhg@gmail.com instead of using the issue tracker.

## Changelog

### v1.0.0

- Initial release
- AES-256-CBC encryption/decryption
- TypeScript support
- Comprehensive error handling
- Full test coverage