1. Frontend (Angular) - AES Encryption
In Angular, you'll use the crypto-js
library to perform AES encryption. Here's how to set it up and encrypt data:
Step 1: Install crypto-js
You can install crypto-js
via npm:
bashnpm install crypto-js
Step 2: Implement AES Encryption in Angular
In your Angular service or component, you can encrypt the data like this:
typescript
import * as CryptoJS from 'crypto-js';
export class EncryptionService {
private secretKey = 'your-secret-key'; // Your secret key
encryptData(data: string): string {
const ciphertext = CryptoJS.AES.encrypt(data, this.secretKey).toString();
return ciphertext;
}
decryptData(encryptedData: string): string {
const bytes = CryptoJS.AES.decrypt(encryptedData, this.secretKey);
const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
return decryptedData;
}
}
encryptData()
: Encrypts the inputdata
using AES encryption and returns the encrypted string.decryptData()
: Decrypts the encrypted data using the same secret key.
Step 3: Use the Encryption Service
You can now use this service in your components to encrypt or decrypt data:
typescript
import { Component } from '@angular/core';
import { EncryptionService } from './encryption.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
encryptedData: string;
decryptedData: string;
constructor(private encryptionService: EncryptionService) { }
encryptMessage(message: string) {
this.encryptedData = this.encryptionService.encryptData(message);
console.log('Encrypted Data:', this.encryptedData);
}
decryptMessage() {
this.decryptedData = this.encryptionService.decryptData(this.encryptedData);
console.log('Decrypted Data:', this.decryptedData);
}
}
2. Backend (ASP.NET) - AES Encryption
In .NET, you can use the System.Security.Cryptography
namespace to handle AES encryption. Here's how you can implement it:
Step 1: AES Encryption and Decryption in .NET
Here's an example of how to implement AES encryption and decryption in an ASP.NET Web API or service:
csharp
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AESEncryptionService
{
private string secretKey = "your-secret-key"; // Secret key (same as Angular)
public string Encrypt(string plainText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(secretKey);
aesAlg.IV = new byte[16]; // Initialize IV to 0 (or you could generate a random one)
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
public string Decrypt(string cipherText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(secretKey);
aesAlg.IV = new byte[16]; // Same IV as encryption
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
Step 2: Use AES in Your .NET Controller (API Endpoint)
You can create an API endpoint that accepts encrypted data and decrypts it.
csharp
[ApiController]
[Route("api/[controller]")]
public class EncryptionController : ControllerBase
{
private readonly AESEncryptionService _encryptionService;
public EncryptionController(AESEncryptionService encryptionService)
{
_encryptionService = encryptionService;
}
[HttpPost("encrypt")]
public ActionResult<string> EncryptData([FromBody] string plainText)
{
string encryptedData = _encryptionService.Encrypt(plainText);
return Ok(encryptedData);
}
[HttpPost("decrypt")]
public ActionResult<string> DecryptData([FromBody] string cipherText)
{
string decryptedData = _encryptionService.Decrypt(cipherText);
return Ok(decryptedData);
}
}
3. Communicating Between Angular and .NET Backend
Now that you have encryption set up in both Angular and .NET, you can send the encrypted data from the Angular frontend to the .NET backend, and the backend can decrypt it and process the data. For example, use HttpClient
in Angular to send the encrypted data to the backend:
typescript
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EncryptionService {
private apiUrl = 'http://localhost:5000/api/encryption';
constructor(private http: HttpClient) { }
encryptData(data: string) {
// Encrypt data first in Angular
const encryptedData = this.encryptMessage(data);
// Send encrypted data to the backend
this.http.post(`${this.apiUrl}/encrypt`, encryptedData)
.subscribe(response => console.log(response));
}
private encryptMessage(data: string): string {
// Implement your encryption logic here
return data; // Return the encrypted data
}
}
4. Important Considerations
Key Management: The key (
secretKey
) used in both Angular and .NET should be securely managed. Never hard-code sensitive keys in production code. Instead, use environment variables or a secure key management system.Security: You may want to consider using secure random initialization vectors (IVs) and hashing techniques to improve security. Also, always use HTTPS to protect the transmission of sensitive data.
Cross-Origin Requests: If your Angular frontend and .NET backend are hosted on different domains, ensure that you have proper CORS (Cross-Origin Resource Sharing) configuration on the backend.
By following these steps, you can successfully handle AES encryption in both Angular and .NET
Secure Key Management Solution
Instead of exposing the key in Angular, you can:
- Store the key securely on the backend (e.g., in environment variables or a key management system).
- Generate or retrieve the key dynamically on the backend.
- Use secure communication (HTTPS) to send the key from the backend to Angular (temporarily for encryption).
- Ensure the key is never stored or exposed in the Angular code after it is used for encryption.
Here’s a solution to achieve this:
Step-by-Step Solution
- Backend (ASP.NET) - Key Generation and Distribution
In your backend (ASP.NET), you can securely generate and manage the AES key.
Example of Key Management in .NET
- Store the secret key securely in the backend: You can retrieve the secret key from environment variables, configuration files, or use a dedicated Key Management System (KMS) like Azure Key Vault or AWS KMS.
- Send the key to the frontend securely over HTTPS.
For example, let’s say you retrieve the key securely from an environment variable on the server.
csharp
public class AESEncryptionService
{
// Secret key is retrieved from a secure place like environment variable
private string secretKey = Environment.GetEnvironmentVariable("AES_SECRET_KEY");
public string Encrypt(string plainText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(secretKey);
aesAlg.IV = new byte[16]; // Use a fixed IV or generate one securely
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,
CryptoStreamMode.Write))
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
public string Decrypt(string cipherText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(secretKey);
aesAlg.IV = new byte[16]; // Fixed IV or a randomly generated IV
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
Endpoint to Provide the Key Temporarily to Angular (HTTPS only)
In some cases, you can expose an endpoint that will send the AES key to the frontend only during the encryption session.
For example, your API could look like this:
csharp
[ApiController]
[Route("api/[controller]")]
public class EncryptionController : ControllerBase
{
private readonly AESEncryptionService _encryptionService;
public EncryptionController(AESEncryptionService encryptionService)
{
_encryptionService = encryptionService;
}
[HttpGet("get-key")]
public ActionResult<string> GetKey()
{
// Ensure this is done securely, use HTTPS, and only provide key for short periods
return Ok(_encryptionService.GetSecretKey());
}
[HttpPost("encrypt")]
public ActionResult<string> EncryptData([FromBody] string plainText)
{
string encryptedData = _encryptionService.Encrypt(plainText);
return Ok(encryptedData);
}
[HttpPost("decrypt")]
public ActionResult<string> DecryptData([FromBody] string cipherText)
{
string decryptedData = _encryptionService.Decrypt(cipherText);
return Ok(decryptedData);
}
}
2. Frontend (Angular) - Secure Key Handling
In Angular, you should never hard-code the key. Instead, request the key securely from your .NET backend when needed. The process is as follows:
- Request the AES Key from the Backend (via HTTPS)
- Use the Key for AES Encryption in Angular for the specific session or transaction.
- Avoid Storing the Key: The key should not be stored in Angular after use. It should be used temporarily for encryption and immediately discarded.
Example of Angular Service to Get the Key
typescript
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';
@Injectable({
providedIn: 'root'
})
export class EncryptionService {
private apiUrl = 'https://yourapi.com/api/encryption';
constructor(private http: HttpClient) { }
// This function will call your .NET API to get the key
getAESKey() {
return this.http.get<string>(`${this.apiUrl}/get-key`);
}
encryptData(data: string): string {
// Step 1: Get the key from the backend securely
this.getAESKey().subscribe((key: string) => {
// Step 2: Use the key for encryption
const encryptedData = CryptoJS.AES.encrypt(data, key).toString();
console.log('Encrypted Data:', encryptedData);
});
}
decryptData(encryptedData: string): string {
// Step 1: Get the key from the backend securely
this.getAESKey().subscribe((key: string) => {
// Step 2: Use the key for decryption
const bytes = CryptoJS.AES.decrypt(encryptedData, key);
const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
console.log('Decrypted Data:', decryptedData);
return decryptedData;
});
}
}
3. Ensure Secure Communication
- Always use HTTPS to encrypt the transmission of the AES key between Angular and the backend. This ensures that the key is not exposed to potential attackers during transit.
- Ensure token-based authentication (e.g., JWT) or other authentication mechanisms are used so only authorized users can request the AES key.
4. Short-Lived Key Management
- You can use session-based keys that are retrieved from the backend for each session, and they expire after a short period or after the session ends.
- Rotate keys regularly to limit the exposure in case a key is compromised.
Conclusion
By following the above process, the AES key remains securely stored on the backend, and it is never exposed to the frontend or stored in Angular code. Angular only retrieves the key temporarily for encryption and decryption over a secure HTTPS connection.
This approach ensures that your sensitive encryption keys are kept secure and that they are never directly exposed to the client-side (Angular) code.
Overview of Secure Key Management Services
Popular cloud providers offer Key Management Services (KMS) that integrate with other services to help you manage cryptographic keys securely. These services include:
- AWS Key Management Service (AWS KMS)
- Azure Key Vault
- Google Cloud Key Management
These services handle sensitive key storage, rotation, and access policies in a highly secure and compliant manner. They also provide auditing capabilities to monitor who accesses the keys and how they are used.
Here’s how you can use a Key Management Service (such as Azure Key Vault or AWS KMS) to store and manage AES keys without exposing them in the frontend (Angular) code.
I'll go over two examples using AWS KMS and Azure Key Vault for securely managing and retrieving the AES key.
Example 1: AWS Key Management Service (AWS KMS)
AWS KMS helps you create and manage cryptographic keys. You can use AWS KMS to securely manage the encryption key without having to manually handle it in your application.
Step 1: Set Up AWS KMS
Create a Key in AWS KMS:
- In the AWS Management Console, go to AWS KMS.
- Create a new Customer Master Key (CMK). You can choose symmetric encryption keys (suitable for AES).
- Set up key policies that control access to the key.
Install AWS SDK in your .NET backend: You need to install the AWS SDK for .NET, which provides tools to interact with AWS services, including KMS.
bashInstall-Package AWSSDK.KeyManagementService
Step 2: Using AWS KMS in .NET
You will interact with the AWS KMS service to retrieve or encrypt/decrypt using the AES key.
csharp
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
using System;
using System.Text;
public class KMSService
{
private readonly string keyId = "your-kms-key-id"; // AWS KMS Key ID
private readonly AmazonKeyManagementServiceClient kmsClient;
public KMSService()
{
kmsClient = new AmazonKeyManagementServiceClient();
}
// Encrypt data using the AES key managed by KMS
public string Encrypt(string plainText)
{
var encryptRequest = new EncryptRequest
{
KeyId = keyId,
Plaintext = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(plainText))
};
var encryptResponse = kmsClient.EncryptAsync(encryptRequest).Result;
return Convert.ToBase64String(encryptResponse.CiphertextBlob.ToArray());
}
// Decrypt data using the AES key managed by KMS
public string Decrypt(string cipherText)
{
var decryptRequest = new DecryptRequest
{
CiphertextBlob = new System.IO.MemoryStream(Convert.FromBase64String(cipherText))
};
var decryptResponse = kmsClient.DecryptAsync(decryptRequest).Result;
return Encoding.UTF8.GetString(decryptResponse.Plaintext.ToArray());
}
}
Step 3: Using AWS KMS in Angular (Backend Communication)
In your Angular app, you should never interact directly with AWS KMS. Instead, your Angular app will communicate with your backend, which will handle all key management securely. Angular should request encrypted data and receive the encrypted response.
Example Angular service to send data for encryption:
typescript
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EncryptionService {
private apiUrl = 'https://yourapi.com/api/encryption';
constructor(private http: HttpClient) { }
// Request to encrypt data
encryptData(data: string) {
return this.http.post(`${this.apiUrl}/encrypt`, { data });
}
// Request to decrypt data
decryptData(encryptedData: string) {
return this.http.post(`${this.apiUrl}/decrypt`, { encryptedData });
}
}
The backend API would securely interact with AWS KMS to encrypt or decrypt data, while Angular only sends and receives encrypted data.
Example 2: Azure Key Vault
Azure Key Vault is a cloud service for securely managing keys, secrets, and certificates. It integrates well with Azure-based applications and provides APIs for key management.
Step 1: Set Up Azure Key Vault
Create a Key Vault in the Azure Portal:
- In the Azure portal, go to Key Vaults and create a new vault.
- Add a Key to the vault. You can generate an AES key or use your own key.
- Set Access Policies to define who can access and manage the key.
Set Up Azure SDK for .NET: You need to install the Azure.Identity and Azure.Security.KeyVault.Keys libraries.
bashInstall-Package Azure.Identity Install-Package Azure.Security.KeyVault.Keys
Step 2: Using Azure Key Vault in .NET
Once you have your key stored in Azure Key Vault, you can retrieve it securely in your .NET backend.
csharp
using Azure.Identity;
using Azure.Security.KeyVault.Keys;
using System;
using System.Text;
public class KeyVaultService
{
private string keyVaultUrl = "https://your-keyvault-name.vault.azure.net";
private string keyName = "your-key-name";
private KeyClient keyClient;
public KeyVaultService()
{
keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
}
// Encrypt using Key Vault
public string Encrypt(string plainText)
{
KeyVaultKey key = keyClient.GetKey(keyName);
var encryptResult = keyClient.Encrypt("AES", Encoding.UTF8.GetBytes(plainText));
return Convert.ToBase64String(encryptResult.Ciphertext);
}
// Decrypt using Key Vault
public string Decrypt(string cipherText)
{
KeyVaultKey key = keyClient.GetKey(keyName);
var decryptResult = keyClient.Decrypt("AES", Convert.FromBase64String(cipherText));
return Encoding.UTF8.GetString(decryptResult.Plaintext);
}
}
Step 3: Using Azure Key Vault in Angular (Backend Communication)
Again, Angular does not interact directly with the Azure Key Vault. The frontend sends encrypted data to the backend, and the backend retrieves the key from Azure Key Vault to perform encryption and decryption.
Example Angular service to send encrypted data:
typescript
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EncryptionService {
private apiUrl = 'https://yourapi.com/api/encryption';
constructor(private http: HttpClient) { }
// Request to encrypt data
encryptData(data: string) {
return this.http.post(`${this.apiUrl}/encrypt`, { data });
}
// Request to decrypt data
decryptData(encryptedData: string) {
return this.http.post(`${this.apiUrl}/decrypt`, { encryptedData });
}
}
Key Management Best Practices
- Key Rotation: Both AWS KMS and Azure Key Vault support automatic key rotation. It's important to regularly rotate your keys to reduce the risk of compromise.
- Key Access Control: Use IAM (Identity and Access Management) roles and policies to control who can access the key and under what circumstances.
- Audit Logging: Both services offer logging and auditing features to monitor access to keys and detect potential misuse.
- Encrypt Data in Transit: Always use HTTPS to encrypt the communication between the frontend (Angular) and backend, ensuring that the encryption keys and encrypted data are protected during transmission.
- Secure Backend: Ensure that your backend API that interacts with the KMS is well-secured and follows best practices, including token-based authentication (JWT or OAuth2).
Conclusion
Using a Key Management Service (KMS) like AWS KMS or Azure Key Vault offers a secure and centralized way to store and manage cryptographic keys. The frontend (Angular) will never directly interact with the keys but will rely on the backend to retrieve and use them to encrypt or decrypt data. This ensures that sensitive keys are never exposed in the frontend code, significantly enhancing security.
By leveraging these KMS services, you ensure that:
- Key management is centralized and controlled.
- Sensitive keys are stored securely, with access policies and audit trails.
- Encryption operations are handled by the backend, and the frontend only deals with encrypted data.
Here’s how you can handle session-based keys in Angular and ASP.NET securely:
Key Concepts
- Session-based Key: A new encryption key is generated for each session (or per request), used temporarily for encryption/decryption, and expires after a short period or at the end of the session.
- Backend (ASP.NET): The server generates the session-based AES key and stores it temporarily, handling encryption and decryption operations.
- Frontend (Angular): The frontend requests the AES key from the backend at the beginning of the session and uses it for encryption/decryption during the session.
Example Flow:
- Backend: When a session starts, generate a random AES key and store it in a secure, in-memory store or database. You may also store the expiration time of the key. When the session ends or the key expires, delete it from the store.
- Frontend (Angular): On the first request, Angular retrieves the session key from the backend, then uses it for encryption. The key is used only for that session, and once the session ends, it is discarded.
Implementation Overview
Backend (ASP.NET):
- Generate a new AES key for each session.
- Return the key to the frontend in a secure manner (e.g., via HTTPS).
- Expire the key after a certain time or when the session ends.
Frontend (Angular):
- Request the AES key from the backend at the beginning of the session.
- Use the key for encryption/decryption.
- Discard the key after the session ends.
Backend: ASP.NET Example
In this example, we'll use ASP.NET Core to generate and manage session-based AES keys. We will also store the key in memory and set an expiration time for it.
Step 1: Generate a Session-Based AES Key in ASP.NET
csharp
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace EncryptionDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EncryptionController : ControllerBase
{
private static Dictionary<string, (string key, DateTime expirationTime)> sessionKeys = new();
// Endpoint to get a session-based key
[HttpGet("get-session-key")]
public ActionResult<string> GetSessionKey()
{
var sessionId = HttpContext.Session.Id; // Use the session ID
to associate the key with the session
// Check if the key already exists and has not expired
if (sessionKeys.ContainsKey(sessionId) && sessionKeys[sessionId].expirationTime >
DateTime.UtcNow)
{
return Ok(sessionKeys[sessionId].key);
}
// Generate a new AES key for the session
var newKey = GenerateAESKey();
var expirationTime = DateTime.UtcNow.AddMinutes(5); // Set expiration
time (5 minutes)
// Store the key in the session store (memory in this case)
sessionKeys[sessionId] = (newKey, expirationTime);
return Ok(newKey);
}
// Endpoint to encrypt data using the session-based key
[HttpPost("encrypt")]
public ActionResult<string> Encrypt([FromBody] string plainText)
{
var sessionId = HttpContext.Session.Id;
if (!sessionKeys.ContainsKey(sessionId) || sessionKeys[sessionId].expirationTime
< DateTime.UtcNow)
{
return Unauthorized("Session expired or no key available");
}
var aesKey = sessionKeys[sessionId].key;
var encryptedData = EncryptData(plainText, aesKey);
return Ok(encryptedData);
}
// Endpoint to decrypt data using the session-based key
[HttpPost("decrypt")]
public ActionResult<string> Decrypt([FromBody] string cipherText)
{
var sessionId = HttpContext.Session.Id;
if (!sessionKeys.ContainsKey(sessionId) || sessionKeys[sessionId].expirationTime < DateTime.UtcNow)
{
return Unauthorized("Session expired or no key available");
}
var aesKey = sessionKeys[sessionId].key;
var decryptedData = DecryptData(cipherText, aesKey);
return Ok(decryptedData);
}
private string GenerateAESKey()
{
using (var aes = Aes.Create())
{
aes.GenerateKey();
return Convert.ToBase64String(aes.Key);
}
}
private string EncryptData(string plainText, string base64Key)
{
var key = Convert.FromBase64String(base64Key);
using (var aes = Aes.Create())
{
aes.Key = key;
aes.GenerateIV();
var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (var ms = new System.IO.MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var sw = new System.IO.StreamWriter(cs))
{
sw.Write(plainText);
}
var iv = Convert.ToBase64String(aes.IV);
var encryptedData = Convert.ToBase64String(ms.ToArray());
return $"{iv}:{encryptedData}";
}
}
}
private string DecryptData(string cipherText, string base64Key)
{
var key = Convert.FromBase64String(base64Key);
var parts = cipherText.Split(':');
var iv = Convert.FromBase64String(parts[0]);
var encryptedData = Convert.FromBase64String(parts[1]);
using (var aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (var ms = new System.IO.MemoryStream(encryptedData))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var sr = new System.IO.StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
In the above example:
- The
GetSessionKey
endpoint generates a new AES key when the session starts or when the key expires. - The key is stored in a static dictionary (
sessionKeys
) for simplicity, but in a production environment, you might use a more persistent store or in-memory cache (e.g., Redis). - Expiration: The AES key expires after 5 minutes, and after this time, it will need to be refreshed.
- Encrypt/Decrypt: The
encrypt
anddecrypt
endpoints handle encryption and decryption using the AES key associated with the session.
Step 2: Session Management in .NET
To manage sessions, ensure your ASP.NET Core app is configured to use session storage.
In Startup.cs, configure session:
csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache(); // In-memory cache for sessions
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.IdleTimeout = TimeSpan.FromMinutes(30); // Set session timeout
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession(); // Enable session middleware
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Frontend: Angular Example
The Angular application will request the AES key from the backend and use it for encryption/decryption during the session.
Step 1: Angular Service to Handle Key Retrieval
typescript
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';
@Injectable({
providedIn: 'root'
})
export class EncryptionService {
private apiUrl = 'https://yourapi.com/api/encryption';
constructor(private http: HttpClient) { }
// Request the AES key from the backend
getAESKey() {
return this.http.get<string>(`${this.apiUrl}/get-session-key`);
}
// Encrypt data using AES
encryptData(data: string): void {
this.getAESKey().subscribe((key: string) => {
const encrypted = CryptoJS.AES.encrypt(data, key).toString();
console.log('Encrypted:', encrypted);
});
}
// Decrypt data using AES
decryptData(encryptedData: string): void {
this.getAESKey().subscribe((key: string) => {
const bytes = CryptoJS.AES.decrypt(encryptedData, key);
const decrypted = bytes.toString(CryptoJS.enc.Utf8);
console.log('Decrypted:', decrypted);
});
}
}
Step 2: Using the Service in Angular Components
typescript
import { Component } from '@angular/core';
import { EncryptionService } from './encryption.service';
@Component({
selector: 'app-root',
template: `<button (click)="testEncryption()">Encrypt Data</button>`,
})
export class AppComponent {
constructor(private encryptionService: EncryptionService) {}
testEncryption() {
const data = "Sensitive Information";
this.encryptionService.encryptData(data);
}
}
Conclusion
This setup ensures that:
- The key is securely generated and used for only the duration of the session.
- The key is never exposed in the frontend (Angular).
- Session expiration ensures that the key cannot be reused after a set period.
- Angular simply communicates with the backend to retrieve the key and perform encryption/decryption.
By combining session-based keys with secure storage and expiration mechanisms, you significantly improve the security of your encryptionprocess.
No comments:
Post a Comment