<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Kishan Maurya</title>
    <description>The latest articles on DEV Community by Kishan Maurya (@kishanhimself).</description>
    <link>https://dev.to/kishanhimself</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F423813%2F6fce830d-9ba4-4a0c-85b4-c3486008b119.jpg</url>
      <title>DEV Community: Kishan Maurya</title>
      <link>https://dev.to/kishanhimself</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/kishanhimself"/>
    <language>en</language>
    <item>
      <title>🚀Secure API-to-API Communication with HMAC: Implementation using NestJS, AWS, and Postman🔥</title>
      <dc:creator>Kishan Maurya</dc:creator>
      <pubDate>Tue, 17 Dec 2024 18:36:03 +0000</pubDate>
      <link>https://dev.to/kishanhimself/secure-api-to-api-communication-with-hmac-implementation-using-nestjs-aws-and-postman-38pd</link>
      <guid>https://dev.to/kishanhimself/secure-api-to-api-communication-with-hmac-implementation-using-nestjs-aws-and-postman-38pd</guid>
      <description>&lt;p&gt;Introduction&lt;br&gt;
In today’s interconnected systems, security is crucial for API communication. HMAC (Hash-based Message Authentication Code) is a powerful method to ensure both integrity and authenticity in API calls.&lt;/p&gt;



&lt;p&gt;In this article, we’ll cover:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How HMAC works for API-to-API calls.&lt;/li&gt;
&lt;li&gt;Step-by-step HMAC setup using NestJS and AWS (with UseGuards).&lt;/li&gt;
&lt;li&gt;Postman testing of HMAC-protected endpoints using a custom script.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;1. How HMAC Works for API-to-API Calls&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is HMAC?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;HMAC combines a secret key and message to generate a unique hash. This ensures:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Integrity: The message hasn’t been tampered with.&lt;/li&gt;
&lt;li&gt;Authenticity: The request comes from a trusted sender.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Visual Diagram:&lt;/strong&gt;&lt;br&gt;
How HMAC works&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F547gfroz5dovtfdtdxu4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F547gfroz5dovtfdtdxu4.jpg" alt="hmac" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HMAC Flow&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Client: Generates the HMAC hash using a secret key and the request payload.&lt;/li&gt;
&lt;li&gt;Server: Computes the hash on its end using the same secret key.&lt;/li&gt;
&lt;li&gt;Validation: If both hashes match, the request is valid.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;2. HMAC Setup Using NestJS and AWS&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Install Dependencies&lt;/strong&gt;&lt;br&gt;
Install necessary libraries:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install crypto aws-sdk @nestjs/config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Step 2: Store the Secret Key in AWS Secrets Manager&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go to AWS Console → Secrets Manager → Create a Secret.&lt;/li&gt;
&lt;li&gt;Add your secret key securely.&lt;/li&gt;
&lt;li&gt;Retrieve this key in your NestJS application.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Visual Step-by-Step:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbecx58lvpajyel7xt35k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbecx58lvpajyel7xt35k.png" alt="hmac1" width="800" height="493"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Step 3: Create the HMAC Service&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;hmac.service.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@nestjs/common';
import * as crypto from 'crypto';
import { SecretsManager } from 'aws-sdk';

@Injectable()
export class HmacService {
  private secretKey: string;

  constructor() {
    this.loadSecret();
  }

  async loadSecret() {
    const secretsManager = new SecretsManager({ region: 'us-east-1' });
    const secret = await secretsManager
      .getSecretValue({ SecretId: 'your-secret-key' })
      .promise();
    this.secretKey = secret.SecretString || '';
  }

  generateHmac(payload: string): string {
    return crypto
      .createHmac('sha256', this.secretKey)
      .update(payload)
      .digest('hex');
  }

  validateHmac(payload: string, clientHash: string): boolean {
    const serverHash = this.generateHmac(payload);
    return serverHash === clientHash;
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Use Guards for HMAC Validation&lt;/strong&gt;&lt;br&gt;
Instead of middleware, create a guard to validate HMAC hashes.&lt;/p&gt;

&lt;p&gt;hmac.guard.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { HmacService } from './hmac.service';

@Injectable()
export class HmacGuard implements CanActivate {
  constructor(private readonly hmacService: HmacService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const payload = JSON.stringify(request.body);
    const clientHmac = request.headers['x-hmac-signature'] as string;

    if (!clientHmac || !this.hmacService.validateHmac(payload, clientHmac)) {
      throw new UnauthorizedException('Invalid HMAC signature');
    }

    return true; // Allow request if HMAC is valid
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Apply UseGuards to Routes&lt;/strong&gt;&lt;br&gt;
app.controller.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Controller, Post, Body, UseGuards } from '@nestjs/common';
import { HmacGuard } from './hmac.guard';

@Controller('secure-endpoint')
export class AppController {
  @Post()
  @UseGuards(HmacGuard)
  handleSecureEndpoint(@Body() data: any) {
    return { message: 'Request successfully validated!', data };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Visual Representation :-&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo2jsl7j3fiw6azypjd0s.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo2jsl7j3fiw6azypjd0s.jpg" alt="Image2" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Testing HMAC-Secured Endpoint Using Postman&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Add Pre-request Script&lt;/strong&gt;&lt;br&gt;
Generate the HMAC hash dynamically in Postman:&lt;/p&gt;

&lt;p&gt;Pre-request Script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const crypto = require('crypto');

// Payload
const payload = JSON.stringify({
  data: 'Sample request payload',
});

// Secret Key (replace with your key)
const secretKey = 'your-shared-secret-key';

// Generate HMAC Hash
const hash = crypto
  .createHmac('sha256', secretKey)
  .update(payload)
  .digest('hex');

// Add HMAC hash to headers
pm.request.headers.add({
  key: 'x-hmac-signature',
  value: hash,
});

console.log('Generated HMAC:', hash);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Configure Postman Request&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Method: POST&lt;/li&gt;
&lt;li&gt;Headers: Automatically set by the script.&lt;/li&gt;
&lt;li&gt;Body: Add payload in JSON format.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example Payload:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "data": "Sample request payload"
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Test and Verify&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hit Send.&lt;/li&gt;
&lt;li&gt;If the HMAC is valid, you’ll receive a 200 OK response.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By implementing HMAC using NestJS and testing with Postman, you can ensure:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Integrity and authenticity in API-to-API communication.&lt;/li&gt;
&lt;li&gt;A clean, modular approach using UseGuards for route protection.&lt;/li&gt;
&lt;li&gt;Secure key management with AWS Secrets Manager.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use HMAC Guards for scalable and modular validation.&lt;/li&gt;
&lt;li&gt;Securely manage shared secrets using AWS Secrets Manager.&lt;/li&gt;
&lt;li&gt;Test HMAC validation easily with Postman scripts.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Let me know how you implement HMAC in your systems! 🚀&lt;br&gt;
Connect with me for more API security insights.&lt;/p&gt;




&lt;h1&gt;
  
  
  NestJS #AWS #HMAC #APISecurity #Postman #BackendDevelopment #SpringBoot #JavaDevelopment #Microservices #SpringCloud #BackendDevelopment #RESTAPI #DevTools #SoftwareEngineering #SpringBootTesting #JWTAuthentication #DistributedTracing #EventDrivenArchitecture #EurekaServer #SpringSecurity #APIIntegration #Technology #Programming #Coding #SoftwareEngineering #TechInnovation #TechCommunity  #JavaScript #Python #TypeScript #Golang #Java #RubyOnRails #CSharp #PHP #Swift #Kotlin  #Rust #SQL #HTML #CSS  #NodeJS #ReactJS #AngularJS #VueJS #Django #Flask #SpringBoot  #CloudComputing #Blockchain #AI #MachineLearning #APIDevelopment #CyberSecurity  #ScalableArchitecture #BackendDevelopment #DevOps#AWS#Terraform #DynamoDB #NestJS#CleanCode #TechTrends #Upskilling #TechCareer #Innovation #BestPractices
&lt;/h1&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>nestjs</category>
    </item>
    <item>
      <title>Selection Sort Algorithms</title>
      <dc:creator>Kishan Maurya</dc:creator>
      <pubDate>Sun, 05 Jul 2020 17:29:09 +0000</pubDate>
      <link>https://dev.to/kishanhimself/selection-sort-algorithms-2i9n</link>
      <guid>https://dev.to/kishanhimself/selection-sort-algorithms-2i9n</guid>
      <description>&lt;p&gt;Selection sort is an algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list.&lt;/p&gt;

&lt;p&gt;How Selection Sort Works?&lt;br&gt;
Set the first element as minimum.&lt;br&gt;
Selection Sort Steps&lt;br&gt;
Select first element as minimum&lt;br&gt;
Compare minimum with the second element. If the second element is smaller than minimum, assign the second element as minimum.&lt;/p&gt;

&lt;p&gt;Compare minimum with the third element. Again, if the third element is smaller, then assign minimum to the third element otherwise do nothing. The process goes on until the last element.&lt;br&gt;
Selection Sort Steps&lt;br&gt;
Compare minimum with the remaining elements&lt;br&gt;
After each iteration, minimum is placed in the front of the unsorted list.&lt;br&gt;
Selection Sort Steps&lt;br&gt;
Swap the first with minimum&lt;br&gt;
For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all the elements are placed at their correct positions.&lt;br&gt;
Selection Sort Steps&lt;br&gt;
The first iteration&lt;/p&gt;

&lt;p&gt;Selection sort steps&lt;br&gt;
The second iteration&lt;/p&gt;

&lt;p&gt;Selection sort steps&lt;br&gt;
The third iteration&lt;/p&gt;

&lt;p&gt;Selection sort steps&lt;br&gt;
The fourth iteration&lt;br&gt;
Selection Sort Algorithm&lt;br&gt;
selectionSort(array, size)&lt;br&gt;
  repeat (size - 1) times&lt;br&gt;
  set the first unsorted element as the minimum&lt;br&gt;
  for each of the unsorted elements&lt;br&gt;
    if element &amp;lt; currentMinimum&lt;br&gt;
      set element as new minimum&lt;br&gt;
  swap minimum with first unsorted position&lt;br&gt;
end selectionSort&lt;br&gt;
Python, Java and C/C++ Examples&lt;br&gt;
Python&lt;br&gt;
Java&lt;br&gt;
C&lt;br&gt;
C++&lt;/p&gt;

&lt;h1&gt;
  
  
  Selection sort in Python
&lt;/h1&gt;

&lt;p&gt;def selectionSort(array, size):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for step in range(size):
    min_idx = step

    for i in range(step + 1, size):

        # to sort in descending order, change &amp;gt; to &amp;lt; in this line
        # select the minimum element in each loop
        if array[i] &amp;lt; array[min_idx]:
            min_idx = i

    # put min at the correct position
    (array[step], array[min_idx]) = (array[min_idx], array[step])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;data = [-2, 45, 0, 11, -9]&lt;br&gt;
size = len(data)&lt;br&gt;
selectionSort(data, size)&lt;br&gt;
print('Sorted Array in Ascending Order:')&lt;br&gt;
print(data)&lt;br&gt;
Complexity&lt;br&gt;
Cycle   Number of Comparison&lt;br&gt;
1st (n-1)&lt;br&gt;
2nd (n-2)&lt;br&gt;
3rd (n-3)&lt;br&gt;
... ...&lt;br&gt;
last    1&lt;br&gt;
Number of comparisons: (n - 1) + (n - 2) + (n - 3) + ..... + 1 = n(n - 1) / 2 nearly equals to n2.&lt;/p&gt;

&lt;p&gt;Complexity = O(n2)&lt;/p&gt;

&lt;p&gt;Also, we can analyze the complexity by simply observing the number of loops. There are 2 loops so the complexity is n*n = n2.&lt;/p&gt;

&lt;p&gt;Time Complexities:&lt;/p&gt;

&lt;p&gt;Worst Case Complexity: O(n2)&lt;br&gt;
If we want to sort in ascending order and the array is in descending order then, the worst case occurs.&lt;br&gt;
Best Case Complexity: O(n2)&lt;br&gt;
It occurs when the array is already sorted&lt;br&gt;
Average Case Complexity: O(n2)&lt;br&gt;
It occurs when the elements of the array are in jumbled order (neither ascending nor descending).&lt;br&gt;
The time complexity of the selection sort is the same in all cases. At every step, you have to find the minimum element and put it in the right place. The minimum element is not known until the end of the array is not reached.&lt;/p&gt;

&lt;p&gt;Space Complexity:&lt;/p&gt;

&lt;p&gt;Space complexity is O(1) because an extra variable temp is used.&lt;/p&gt;

&lt;p&gt;Selection Sort Applications&lt;br&gt;
The selection sort is used when:&lt;/p&gt;

&lt;p&gt;a small list is to be sorted&lt;br&gt;
cost of swapping does not matter&lt;br&gt;
checking of all the elements is compulsory&lt;br&gt;
cost of writing to a memory matters like in flash memory (number of writes/swaps is O(n) as compared to O(n2) of bubble sort)&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
