Encryption and Decryption using AES (Symmetric) in Angular

Introduction

AES is a symmetric key algorithm, meaning the same key is used for both encryption and decryption. This is in contrast to asymmetric encryption, where a public key is used for encryption and a private key for decryption.

Key Sizes

AES supports three different key lengths.

  • AES-128: 128-bit key (16 bytes)
  • AES-192: 192-bit key (24 bytes)
  • AES-256: 256-bit key (32 bytes)

Encryption and decryption in angular

Here’s a basic guide on how to implement AES encryption and decryption in Angular using the crypto-js library.

1. Install crypto-js

First, you need to install the crypto-js library.

npm install crypto-js

2. Import crypto-js

Import the necessary components from crypto-js in your Angular service or component.

import * as CryptoJS from 'crypto-js';

3. Encryption and Decryption

You can create utility methods for encryption and decryption using AES.

Encryption

  private secretKey: string = ''; // Replace with a secure key
  private Vector:string =''; // Replace with vector 
 return CryptoJS.AES.encrypt(value, this.secretKey,{
      iv: CryptoJS.enc.Utf8.parse(this.Vector),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,  
      
    }).toString();

Decryption

   const decrypted = CryptoJS.AES.decrypt(encryptedText, this.secretKey, {
      iv:  CryptoJS.enc.Utf8.parse(this.Vector),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
  
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
  • Initialization Vector (IV): Provides uniqueness to the encryption process, making the same plaintext result in different ciphertexts if encrypted multiple times with the same key.
  • Cipher Block Chaining (CBC): Ensures that the encryption of each block depends on the previous one, adding an extra layer of security.
  • PKCS7 Padding: Handles cases where the plaintext doesn't fit perfectly into blocks, ensuring the length matches the block size.

Different types of the mode
 

Cipher Block Chaining (CBC) Mode

  • Description: In CBC mode, each block of plaintext is XORed with the previous ciphertext block before being encrypted. The first block is XORed with an initialization vector (IV). This mode provides strong confidentiality but requires an IV.
  • mode: CryptoJS.mode.CBC

Electronic Codebook (ECB) Mode

  • Description: ECB mode encrypts each block of data independently. This mode is generally not recommended for use because identical plaintext blocks produce identical ciphertext blocks, making it vulnerable to pattern analysis.
  • mode: CryptoJS.mode.ECB

Cipher Feedback (CFB) Mode

  • Description: CFB mode turns a block cipher into a self-synchronizing stream cipher. It encrypts partial blocks, making it suitable for encrypting smaller data such as individual characters or bytes.
  • mode: CryptoJS.mode.CFB

Output Feedback (OFB) Mode

  • Description: OFB mode turns a block cipher into a synchronous stream cipher. It generates keystream blocks, which are XORed with the plaintext to produce ciphertext. Unlike CFB, OFB does not propagate encryption errors.
  • mode: CryptoJS.mode.OFB

Counter (CTR) Mode

  • Description: CTR mode turns a block cipher into a stream cipher. It uses a counter, which is incremented for each block, combined with a nonce (number used once) for encryption. This mode allows parallel encryption of blocks.
  • mode: CryptoJS.mode.CTR

Different types of padding

  • PKCS#7: Common and widely used; compatible with many systems. padding: CryptoJS.pad.Pkcs7
  • ISO10126: Adds randomness, increasing security. padding: CryptoJS.pad.Iso10126
  • ANSI X.923: Uses zero padding except for the last byte indicating the length. padding: CryptoJS.pad.AnsiX923
  • ISO/IEC 7816-4: Starts with 0x80, followed by zeros. padding: CryptoJS.pad.Iso97971
  • Zero Padding: Simple but less secure and may cause issues if the data contains zeros. padding: CryptoJS.pad.ZeroPadding
  • No Padding: No padding added; requires plaintext to be a multiple of the block size. padding: CryptoJS.pad.NoPadding

Key Encoding

Defines the encoding format used for keys and data.

  • UTF-8: The default encoding format used for strings.
  • Hex: Often used for keys or binary data.
  • Base64: Commonly used for encoded keys or encrypted data to ensure safe transmission or storage.
    const utf8Key = CryptoJS.enc.Utf8.parse('mySecretKey'); // UTF-8 Key
    const hexKey = CryptoJS.enc.Hex.parse('0011223344556677'); // Hex Key

Output Format

Determines how the encrypted data is represented.

  • CipherText.toString(): Converts the ciphertext to a Base64 string (default).
  • CipherText.toString(CryptoJS.enc.Hex): Converts the ciphertext to a hexadecimal string.
  • CipherText.toString(CryptoJS.enc.Base64): Explicitly converts to Base64 if needed.
    import { Injectable } from '@angular/core';
    import * as CryptoJS from 'crypto-js';
    
    @Injectable({
      providedIn: 'root'
    })
    export class EncryptionService {
    
      private secretKey: string = ''; // Replace with a secure key
      private Vector:string ='';  // Replace with a vector
      constructor() {}
    
      encrypt(value: string): string {
        return CryptoJS.AES.encrypt(value, this.secretKey,{
          iv: CryptoJS.enc.Utf8.parse(this.Vector),
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7,  
          
        }).toString();
      }
    
      decrypt(encryptedText: string): string {
        const decrypted = CryptoJS.AES.decrypt(encryptedText, this.secretKey, {
          iv:  CryptoJS.enc.Utf8.parse(this.Vector),
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7,
      
        });
        return decrypted.toString(CryptoJS.enc.Utf8);
      }
      encryptObject(value:any):string
      {
        
        return CryptoJS.AES.encrypt(JSON.stringify(value), this.secretKey,{
          iv: CryptoJS.enc.Utf8.parse(this.Vector),
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7,  
          
        }).toString();
      }
    }
    

Output Sample Encrypted text.

Encrypted text


Similar Articles