DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Secure Your Web Applications With Facial Authentication
  • What’s New in the Latest Version of Angular V15?
  • Daily 10 Tech Q&A With Bala
  • Cookies Revisited: A Networking Solution for Third-Party Cookies

Trending

  • The Role of AI in Identity and Access Management for Organizations
  • Advancing Robot Vision and Control
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. How to Secure Your Angular Apps: End-to-End Encryption of API Calls

How to Secure Your Angular Apps: End-to-End Encryption of API Calls

Explore an example of implementing end-to-end encryption of API calls in your secure web app built with Angular.

By 
Kalyan Gottipati user avatar
Kalyan Gottipati
·
Jul. 26, 24 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.3K Views

Join the DZone community and get the full member experience.

Join For Free

When it comes to secure web applications, we must keep sensitive data secure during the communication period. Sadly, while HTTPS encrypts data as it moves from point A to point B, the information is still exposed in a browser's network tab and can leak out this way. In this post, I will give you an example of implementing end-to-end encryption of API calls in your secure web app built with Angular.

Encryption Workflow

Weak protections have traditionally been obfuscation with Base64 encoding or custom schemes. Public key cryptography (PKC) is considered a modern solution to be more secure. It uses a key pair one public key for encryption, and the other private key for decryption. A public key is distributed and a private key is kept on the server.

The encryption workflow is as follows:

  1. Client-side encryption: Your Angular application encrypts the data with the server’s public key before transmitting it to the API. 
  2. Secure transmission: Over an HTTPS connection, the network then transmits the encrypted data. 
  3. Server-side decryption: The server decrypts the data by missioning its private key because it receives the encrypted data, seeing the original information. 
  4. Server-side encryption (Optional): Before sending the response back to the client, the server can also encrypt the data for additional security. 
  5. Client-side decryption: Finally, the client decrypts the encrypted response from the server using a public key stored in the web application.

Implementation Into Angular App

Here is a detailed strategy to implement end-to-end encryption in your Angular financial app.

1. Library Selection and Installation

Choose a well-maintained library like Angular CryptoJS or Sodium for JavaScript, but still put more reliance than loafing in trying to implement them. These libraries contain the APIs for encryption and decryption which is provided by multiple algorithms.

PowerShell
 
npm install crypto-js


2. Key Management

Implement a feature to keep the server's public key safe. There are a couple of common approaches to this:

  • Server-side storage: One relatively simple solution is to store the public key on your backend server, and then retrieve it during application initialization in Angular via an HTTPS request.
  • Key Management Service (Optional): For more advanced set ups, consider a KMS dedicated to secret management, but this requires an extra layer.

3. Create Client-Side Encryption and Decryption Service

Create a common crypto service to handle the application data encryption and decryption.

TypeScript
 
// src/app/services/appcrypto.service.ts
import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';

@Injectable({
  providedIn: 'root'
})
export class AppCryptoService {
  private appSerSecretKey: string = 'server-public-key';

  encrypt(data: any): string {
    return CryptoJS.AES.encrypt(JSON.stringify(data), this.appSerSecretKey).toString();
  }

  decrypt(data: string): any {
    const bytes = CryptoJS.AES.decrypt(data, this.appSerSecretKey);
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
  }
}


4. Application API Call Service

Create a common service to handle the web application's common HTTP methods.

TypeScript
 
// src/app/services/appcommon.service.ts
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AppCryptoService } from '../services/crypto.service';

@Injectable({
  providedIn: 'root'
})
export class AppCommonService {
  constructor(private appCryptoService: AppCryptoService
              private httpClient: HttpClient) {}

  postData(url: string, data: any): Observable<any> {
    const encryptedData = this.appCryptoService.encrypt(data);
    return this.httpClient.post(url, encryptedData);
  }
  
}


5. Server-Side Decryption

On the server side, you have to decrypt all incoming request payloads and encrypt response payloads. Here's an example using Node. js and Express:

JavaScript
 
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto-js');

const app = express();
const secretKey = 'app-secret-key';

app.use(bodyParser.json());

// Using middleware to decrypt the incoming request bodies
app.use((req, res, next) => {
  if (req.body && typeof req.body === 'string') {
    const bytes = crypto.AES.decrypt(req.body, secretKey);
    req.body = JSON.parse(bytes.toString(crypto.enc.Utf8));
  }
  next();
});

// Test post route call
app.post('/api/data', (req, res) => {
  console.log('Decrypted data:', req.body);
  
  // response object
  const responseObj = { message: 'Successfully received' };

  // Encrypt the response body (Optional)
  const encryptedResBody = crypto.AES.encrypt(JSON.stringify(responseBody), secretKey).toString();
  res.send(encryptedResBody);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});


6. Server-Side Encryption (Optional)

The response of the server can also be sent back to the client in an encrypted form for security. This does add a layer of security, though with the caveat that it may impact system performance.

7. Client-Side Decryption (Optional)

When the response is encrypted from the server, decrypt it on the client side. 

Conclusion

This example keeps it simple by using AES encryption. You may want additional encryption mechanisms, depending on your security needs. Don't forget to manage errors and exceptions properly. This is a somewhat crude implementation of encryption in your Angular web app when making API calls around.

API Key management Web application AngularJS security

Opinions expressed by DZone contributors are their own.

Related

  • Secure Your Web Applications With Facial Authentication
  • What’s New in the Latest Version of Angular V15?
  • Daily 10 Tech Q&A With Bala
  • Cookies Revisited: A Networking Solution for Third-Party Cookies

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!