@djangocfg/crypto
Client-side AES-256-GCM decryption for Django-CFG encrypted API responses using Web Crypto API.
Installation
pnpm add @djangocfg/crypto
Features
- AES-256-GCM authenticated decryption
- PBKDF2 key derivation (matches Django-CFG backend)
- Zero dependencies (uses native Web Crypto API)
- TypeScript support with full type inference
- React hooks for declarative decryption
- Per-user and per-session key isolation
Usage
Basic Usage
import { createDecryptionClient } from '@djangocfg/crypto';
const crypto = await createDecryptionClient({
secretKey: 'your-django-secret-key',
userId: 123,
});
const response = await fetch('/api/products/?encrypt=true');
const encryptedData = await response.json();
const data = await crypto.decryptObject(encryptedData);
console.log(data.price);
React Hooks
import { useDecrypt } from '@djangocfg/crypto/react';
function ProductPrice({ product }: { product: Product }) {
const { data, isLoading, error } = useDecrypt(product, {
secretKey: process.env.NEXT_PUBLIC_DECRYPT_KEY!,
userId: user.id,
});
if (isLoading) return <Skeleton />;
if (error) return <ErrorMessage error={error} />;
return <span>${data.price}</span>;
}
Lazy Decryption
import { useLazyDecrypt } from '@djangocfg/crypto/react';
function LazyProduct({ product }: { product: Product }) {
const { decrypt, data, isLoading } = useLazyDecrypt({
secretKey: process.env.NEXT_PUBLIC_DECRYPT_KEY!,
});
return (
<div>
<button onClick={() => decrypt(product)}>
Show Price
</button>
{isLoading && <Spinner />}
{data && <span>{data.price}</span>}
</div>
);
}
API Reference
Core Functions
createDecryptionClient(config)
Creates a decryption client with pre-derived key.
const crypto = await createDecryptionClient({
secretKey: string;
userId?: string|number;
sessionId?: string;
iterations?: number;
keyPrefix?: string;
});
await crypto.decryptField(encryptedField);
await crypto.decryptObject(data);
crypto.isEncryptedField(value);
decryptField(field, key)
Decrypt a single encrypted field.
decryptObject(data, key)
Recursively decrypt all encrypted fields in an object.
React Hooks
useDecrypt(data, config)
Decrypt data on mount.
useDecryptionClient(config)
Create a memoized decryption client.
useLazyDecrypt(config)
Decrypt data on demand with manual trigger.
useIsEncrypted(value)
Check if a value is encrypted.
Types
interface EncryptedField {
encrypted: true;
field?: string;
algorithm: 'AES-256-GCM';
iv: string;
data: string;
auth_tag: string;
}
interface DecryptionConfig {
secretKey: string;
userId?: string | number;
sessionId?: string;
iterations?: number;
keyPrefix?: string;
}
Security Notes
- Never expose your Django
SECRET_KEY directly in frontend code
- Use a dedicated decryption key or derive one securely
- Consider per-user keys for sensitive data isolation
- PBKDF2 iterations must match backend configuration
License
MIT