secure-api-client
v0.1.0
Published
Angular library for client-side API endpoint and payload encryption using AES-CBC.
Downloads
19
Maintainers
Readme
secure-api-client
An Angular library for client-side API endpoint obfuscation and payload encryption using AES-CBC. This package helps enhance your application's security by encrypting sensitive API paths and request bodies, complementing your existing HTTPS/TLS security.
✨ Features
- Endpoint Obfuscation: Encrypts API path segments to hide actual endpoints from casual observation in network requests.
- Payload Confidentiality: Encrypts and decrypts entire request bodies (e.g., JSON data) before transmission.
- Symmetric Encryption: Uses AES-256 in CBC (Cipher Block Chaining) mode with PKCS7 padding.
- Configurable Key: The encryption key is derived from a passphrase provided by the consuming application via Angular's Dependency Injection.
- Dynamic IV Generation: Generates a new, random 16-byte (128-bit) Initialization Vector (IV) for each encryption operation, crucial for security.
- Comprehensive Crypto Utilities: Provides methods for both encryption and decryption of API paths and payloads, along with IV handling helpers.
- URL Encoding/Decoding: Handles necessary URL encoding for encrypted path segments and IVs when used in URLs.
🚀 Installation
Install the library and its peer dependency (crypto-js) using npm:
npm install secure-api-client crypto-js💡 Usage
1. Provide the Encryption Key Passphrase
Your SecureApiClientService requires a secret passphrase from which the encryption key is derived. This passphrase must be provided via Angular's Dependency Injection system using an InjectionToken.
First, create a file for your injection token in your application (e.g., src/app/consts/keyphrase.consts.ts):
// src/app/consts/keyphrase.consts.ts
import { InjectionToken } from '@angular/core';
export const KEY_PASSPHRASE = new InjectionToken<string>('keyPassphrase');Then, in your AppModule (or any other module where you want to provide it), set up the provider. It's highly recommended to load this passphrase from your Angular environment files (e.g., environment.ts or environment.prod.ts) to manage it securely per environment.
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { KEY_PASSPHRASE } from './consts/keyphrase.consts';
import { environment } from '../environments/environment';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{
provide: KEY_PASSPHRASE,
useValue: environment.encryptionKeyPassphrase
}
],
bootstrap: [AppComponent]
})
export class AppModule {}In your environment files:
// src/environments/environment.ts
export const environment = {
production: false,
encryptionKeyPassphrase: 'your_development_secret_key_here'
};// src/environments/environment.prod.ts
export const environment = {
production: true,
encryptionKeyPassphrase: 'YOUR_SUPER_SECRET_PRODUCTION_KEY'
};2. Inject and Use the Service
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SecureApiClientService } from 'secure-api-client';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private baseUrl = 'https://localhost:7241/api/x';
constructor(
private http: HttpClient,
private secureApiClientService: SecureApiClientService
) {}
sendEncryptedRequest(): void {
const iv = this.secureApiClientService.generateIv();
const ivUrlEncodedBase64 = this.secureApiClientService.getIvUrlEncoded(iv);
const actualApiPath = 'application/GetBoardValues';
const payloadData = { boardId: '123', userId: 'abc', status: 'active' };
const encryptedPath = this.secureApiClientService.encryptApiPath(actualApiPath, iv);
const encryptedPayload = this.secureApiClientService.encryptPayload(JSON.stringify(payloadData), iv);
const requestUrl = `${this.baseUrl}/${encryptedPath}?iv=${ivUrlEncodedBase64}`;
this.http.post(requestUrl, encryptedPayload, {
headers: {
'Content-Type': 'text/plain'
}
}).subscribe(
response => {
console.log('Encrypted request successful:', response);
},
error => {
console.error('Encrypted request failed:', error);
}
);
}
testDecryption(): void {
const sampleEncryptedPath = 'PRqtpCvHfQouH4yMhPLpmg%3D%3D';
const sampleIvUrlEncoded = 'jW8PP4WAyPf63xnBluippA%3D%3D';
const sampleEncryptedPayload = 'tyMNcufA1GeK91c/1K6UbFJ3a5eiHiDQqMn5O5JAGPRSnrHREfNsH+xy5aZzqwZsQVQB66GzHeWhhcm/STnB1A==';
const sampleIvBase64 = decodeURIComponent(sampleIvUrlEncoded);
try {
const decryptedPath = this.secureApiClientService.decryptApiPath(sampleEncryptedPath, sampleIvUrlEncoded);
console.log('Decrypted Path:', decryptedPath);
const decryptedPayload = this.secureApiClientService.decryptPayload(sampleEncryptedPayload, sampleIvBase64);
console.log('Decrypted Payload:', decryptedPayload);
} catch (e) {
console.error('Decryption Test Failed:', e);
}
}
getDerivedKeyForDebug(): void {
const derivedKeyHex = this.secureApiClientService.getDerivedKeyHex();
console.log('Derived Key (Hex, for debug):', derivedKeyHex);
}
}🔑 API Reference
SecureApiClientService
Constructor:
constructor(@Inject(KEY_PASSPHRASE) keyPassphrase: string)Initializes the service. The keyPassphrase is used to derive the AES encryption key.
Methods:
generateIv(): CryptoJS.lib.WordArray
Generates a new 16-byte IV.encryptPayload(plainText: string, iv: CryptoJS.lib.WordArray): string
Encrypts a plain text string using AES-CBC.
Returns: Base64 encoded ciphertext.decryptPayload(base64CipherText: string, ivBase64: string): string
Decrypts a Base64 encoded ciphertext string using the provided IV.encryptApiPath(path: string, iv: CryptoJS.lib.WordArray): string
Encrypts and URL-encodes a path segment.decryptApiPath(urlEncodedBase64Path: string, ivUrlEncodedBase64: string): string
Decrypts a URL-encoded path using the encrypted IV.getIvBase64(iv: CryptoJS.lib.WordArray): string
Converts IV to raw Base64 string.getIvUrlEncoded(iv: CryptoJS.lib.WordArray): string
Converts IV to URL-encoded Base64 string.getDerivedKeyHex(): string
Returns the derived AES key in hex (for debugging only).
⚠️ Security Considerations
- Key Management is Paramount: Do not hardcode or expose the passphrase in the client.
- Use HTTPS/TLS: This library supplements HTTPS, not replaces it.
- Unique IV Per Request: Never reuse IVs with the same key.
- Server Support Required: Ensure your backend understands and decrypts the encrypted request properly.
🤝 Contributing
Contributions are welcome! Please open issues or pull requests with bug reports or enhancements.
📄 License
This project is licensed under the MIT License. See the LICENSE file for details.
