# @tigthor/encyption-utils

A simple, secure, and easy-to-use encryption/decryption utility for TypeScript applications. Works seamlessly with both backend APIs and frontend Next.js applications.

## Features

- 🔐 **Secure AES Encryption**: Uses AES-256-CBC encryption with PBKDF2 key derivation
- 🚀 **Easy to Use**: Simple API with both basic and advanced usage patterns
- 🔧 **Configurable**: Customizable encryption parameters
- 🌍 **Universal**: Works in both Node.js and browser environments
- 📝 **TypeScript**: Full TypeScript support with type definitions
- 🧪 **Well Tested**: Comprehensive test coverage
- 📦 **Lightweight**: Minimal dependencies

## Installation

```bash
npm install @tigthor/encyption-utils
```

## Quick Start

### Basic Usage

```typescript
import { quickEncrypt, quickDecrypt } from '@tigthor/encyption-utils';

// Encrypt
const encrypted = quickEncrypt('Hello, World!', 'my-secret-password');
console.log(encrypted); // "salt:iv:encryptedData"

// Decrypt
const decrypted = quickDecrypt(encrypted, 'my-secret-password');
console.log(decrypted); // "Hello, World!"
```

### Advanced Usage with EncryptionManager

```typescript
import { EncryptionManager } from '@tigthor/encyption-utils';

// Create an instance with configuration
const crypto = new EncryptionManager({
  secretKey: 'your-app-secret-key',
  defaultOptions: {
    iterations: 10000,
    keySize: 256,
  },
});

// Encrypt using the configured secret key
const encrypted = crypto.encryptSimple('Sensitive data');
const decrypted = crypto.decryptSimple(encrypted);

// Or encrypt with a specific password
const result = crypto.encrypt('Data to encrypt', 'specific-password');
const original = crypto.decrypt(result, 'specific-password');
```

### Global Instance Pattern

```typescript
import { initializeEncryption, encrypt, decrypt } from '@tigthor/encyption-utils';

// Initialize once in your app
initializeEncryption({ secretKey: 'your-global-secret' });

// Use anywhere in your app
const encrypted = encrypt('My secret message');
const decrypted = decrypt(encrypted);
```

## Usage Examples

### Backend API (Express.js)

```typescript
import express from 'express';
import { EncryptionManager } from '@tigthor/encyption-utils';

const app = express();
const crypto = new EncryptionManager({ secretKey: process.env.ENCRYPTION_KEY });

app.post('/api/secure-data', (req, res) => {
  const sensitiveData = req.body.data;
  
  // Encrypt before storing in database
  const encrypted = crypto.encryptSimple(JSON.stringify(sensitiveData));
  
  // Store encrypted data...
  res.json({ success: true });
});

app.get('/api/secure-data/:id', (req, res) => {
  // Retrieve encrypted data from database...
  const encryptedData = getFromDatabase(req.params.id);
  
  // Decrypt before sending
  const decrypted = JSON.parse(crypto.decryptSimple(encryptedData));
  
  res.json({ data: decrypted });
});
```

### Frontend Next.js

```typescript
// utils/crypto.ts
import { createEncryption } from '@tigthor/encyption-utils';

export const crypto = createEncryption({ 
  secretKey: process.env.NEXT_PUBLIC_ENCRYPTION_KEY 
});

// components/SecureForm.tsx
import { useState } from 'react';
import { crypto } from '../utils/crypto';

export default function SecureForm() {
  const [data, setData] = useState('');

  const handleSubmit = async () => {
    // Encrypt data before sending to API
    const encrypted = crypto.encryptSimple(data);
    
    await fetch('/api/secure-endpoint', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ encryptedData: encrypted }),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        value={data} 
        onChange={(e) => setData(e.target.value)}
        placeholder="Enter sensitive data"
      />
      <button type="submit">Submit Securely</button>
    </form>
  );
}
```

### Environment Variables

```bash
# .env
ENCRYPTION_KEY=your-super-secret-encryption-key-here

# .env.local (Next.js)
NEXT_PUBLIC_ENCRYPTION_KEY=your-frontend-encryption-key
```

## API Reference

### EncryptionManager

The main class for encryption operations.

```typescript
constructor(config?: CryptoConfig)
```

**Methods:**
- `encrypt(plaintext: string, password?: string, options?: EncryptionOptions): EncryptionResult`
- `decrypt(encryptedData: string | EncryptionResult, password?: string, options?: DecryptionOptions): string`
- `encryptSimple(plaintext: string): string`
- `decryptSimple(encryptedString: string): string`
- `setSecretKey(key: string): void`
- `updateConfig(newConfig: Partial<CryptoConfig>): void`

### Quick Functions

Convenient functions for simple use cases:

```typescript
quickEncrypt(plaintext: string, password: string): string
quickDecrypt(encryptedString: string, password: string): string
```

### Factory Functions

```typescript
createEncryption(config?: CryptoConfig): EncryptionManager
initializeEncryption(config: CryptoConfig): EncryptionManager
getEncryption(): EncryptionManager
```

### Utility Functions

```typescript
generateRandomKey(length?: number): string
generateSalt(length?: number): string
generateIV(length?: number): string
hashString(input: string): string
generateHMAC(message: string, key: string): string
verifyHMAC(message: string, key: string, signature: string): boolean
```

## Configuration Options

```typescript
interface CryptoConfig {
  secretKey?: string;
  defaultOptions?: EncryptionOptions;
}

interface EncryptionOptions {
  algorithm?: string;    // Default: 'AES'
  keySize?: number;      // Default: 256
  iterations?: number;   // Default: 10000
}
```

## Security Best Practices

1. **Use Environment Variables**: Never hardcode encryption keys in your source code
2. **Strong Keys**: Use long, random keys (at least 32 characters)
3. **Key Rotation**: Regularly rotate your encryption keys
4. **HTTPS**: Always use HTTPS when transmitting encrypted data
5. **Backend Validation**: Always validate and sanitize data on the backend

## Error Handling

The library throws descriptive errors for common issues:

```typescript
try {
  const encrypted = crypto.encryptSimple('data');
  const decrypted = crypto.decryptSimple(encrypted);
} catch (error) {
  console.error('Encryption error:', error.message);
}
```

## Browser Compatibility

Works in all modern browsers that support:
- ES2020+
- Web Crypto API (for secure random number generation)

## Node.js Compatibility

- Node.js 16+
- Supports both CommonJS and ES Modules

## Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-feature`
3. Make changes and add tests
4. Run tests: `npm test`
5. Commit changes: `git commit -am 'Add new feature'`
6. Push to branch: `git push origin feature/new-feature`
7. Submit a pull request

## License

MIT License - see LICENSE file for details.

## Changelog

### 1.0.0
- Initial release
- AES-256-CBC encryption
- PBKDF2 key derivation
- TypeScript support
- Browser and Node.js compatibility
