usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Dual Key Encryption in JavaScript: A Guide to RSA Implementation



Dual Key Encryption in JavaScript

Dual key encryption, also known as public/private key cryptography, is a core concept in modern data security. It is widely used in secure communications, digital certificates, and encrypted web applications. In this tutorial, you will learn how public and private key encryption works in JavaScript, why it is classified as asymmetric encryption, and how dual keys are used to securely encrypt and decrypt data.

This explanation is designed for tertiary-level students and beginners who want a clear, practical understanding of cryptography concepts without unnecessary complexity.

What Is Dual Key (Public/Private Key) Encryption? | Explanation for JavaScript Kids

Dual key encryption is an encryption method that uses two mathematically related keys:

  • A public key, which is shared openly and used to encrypt data
  • A private key, which is kept secret and used to decrypt data

This approach is formally known as public key cryptography or asymmetric encryption. Unlike symmetric encryption, where the same key is used for both encryption and decryption, dual key encryption ensures that encrypted data can only be decrypted by the intended recipient.

Why Asymmetric Encryption Is Important | Explanation for JavaScript Kids

Asymmetric encryption solves a major problem in secure communication: key sharing. Since the public key can be distributed freely, there is no need to transmit a secret key over an insecure channel.

Key advantages include:

  • Improved security for data transmission
  • Safe communication over public networks
  • Strong authentication mechanisms
  • Foundation for HTTPS, SSL/TLS, and digital signatures

Because of these benefits, public/private key encryption is commonly used in web applications, secure messaging systems, and online banking platforms.


How Dual Key Encryption Works (Step by Step) | Explanation for JavaScript Kids

The dual key encryption process follows a logical sequence:

  1. A key pair is generated (public key and private key)
  2. The sender encrypts data using the public key
  3. The encrypted message is transmitted
  4. The recipient decrypts the message using the private key

Only the matching private key can decrypt the data, even though the public key is visible to everyone. This is what makes asymmetric cryptography secure.

JavaScript Example: Public and Private Key Encryption

In JavaScript, asymmetric encryption can be implemented using cryptographic libraries or the Web Crypto API. The general workflow remains the same regardless of the specific implementation.

A typical JavaScript public/private key encryption process includes:

  • Generating an RSA key pair
  • Encrypting data with the public key
  • Decrypting encrypted data with the private key

This approach allows JavaScript applications to securely handle sensitive information such as passwords, tokens, and confidential messages.


The Mathematics of Public Key Encryption | Math Explanation for JavaScript Kids

At its core, dual key encryption relies on the mathematical difficulty of factoring large numbers. Our JavaScript RSA encryption tutorial focuses on the relationship between prime numbers and modular arithmetic. To generate a secure pair of keys, we follow a rigorous mathematical process:

  1. Prime Selection: Choosing two large prime numbers ( and ) to create a semi-prime modulus.
  2. LCM Calculation: Determining the Lowest Common Multiple of $(p-1)$ and $(q-1)$.
  3. Key Generation: Selecting a Public Key that is coprime to the LCM.
  4. The Inverse: Calculating the Private Key as the modular multiplicative inverse of the Public Key.
  5. Encrypt data: \([Unicode(data)]^{public\_key} % semi_prime = encoded_data;\)
  6. Decrypt data: \([encoded\_data]^{private\_key} % semi_prime = original data;\)

Implementing RSA Logic in JavaScript

While many modern applications use the built-in WebCrypto API, writing a manual RSA implementation is the best way to grasp how ciphertext and plaintext interact.

Using JavaScript's BigInt capability, we can handle the large-scale integer calculations required for secure encryption. Below, we explore the JavaScript code required to transform a standard Unicode string into an encrypted hexadecimal array, ensuring that only the holder of the private key can reverse the process.

Create 2 new files; On Notepad++: File, New.
Call them DualKeyEncryption.html and DualKeyEncryption.js respectively.
Type out the adjoining JavaScript code for encrypting and decrypting a chunk of data using a Public Key - Private Key pair.


By The Way: The encryption algorithm described in the above steps is called R.S.A. algorithm; and coming up with an algorithm that can factor very large semi primes into their prime factors in linear time is called the R.S.A. problem.

Also noteworthy is the fact that there are other ways of implementing an open-lock-only encryption algorithm; like the Logarithm Encryption, e.t.c.

The script for finding LCM in JavaScript has been explained in the Primary Category.
Just make a copy of it to your current directory.


Why Use RSA in JavaScript?

  • Educational Value: Great for learning cryptography concepts.
  • Practical Applications: Secure login systems, encrypted messaging, and digital signatures.
  • Flexibility: JavaScript runs everywhere — browsers, servers, and mobile apps.

Dual Key Encryption vs Symmetric Encryption | Explanation for JavaScript Kids

It is important to distinguish between symmetric encryption and dual key encryption:

Symmetric vs Asymmetric Encryption Differences
FeatureSymmetric EncryptionDual Key Encryption
Number of keysOne shared keyTwo separate keys
SecurityLower for key exchangeHigher for communication
SpeedFasterSlower
Common useData storageSecure communication

In practice, many systems use both methods together, combining the speed of symmetric encryption with the security of asymmetric encryption.

Common Uses of Public/Private Key Cryptography | Explanation for JavaScript Kids

Public and private key encryption is used in many real-world applications, including:

  • Secure web communication (HTTPS)
  • Digital certificates and authentication
  • Secure email systems
  • Encrypted file sharing
  • Secure API communication

Understanding dual key encryption in JavaScript provides a strong foundation for learning advanced security and cryptography topics.


Key Takeaways from the JavaScript Dual Key Encryption Algorithm

  • Dual key encryption uses a public key for encryption and a private key for decryption
  • It is also known as public/private key cryptography or asymmetric encryption
  • JavaScript supports public key encryption through cryptographic APIs and libraries
  • This method is essential for secure communication on the web

Summary: JavaScript Dual Key Encryption Algorithm

By understanding RSA encryption in JavaScript, you gain insight into how modern cryptography protects sensitive information. Whether you're a student exploring modular arithmetic or a developer implementing public/private key cryptography, this tutorial provides the foundation you need.










JavaScript Code for Dual Key Encryption - .html

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Dual Key Encryption</title>
        <script src="LCM.js"></script>
        <script src="DualKeyEncryption.js"></script>
    </head>
    <body>

        <h3>Public / Private Key Encryption</h3>
        <!-- This is where the result will be displayed when it is ready.-->
        <div id="word_encrypt"></div>

        <script>
            /*
             * STEP I: Pick two prime numbers
             */

            const p1 = 101// 1st prime
            const p2 = 401// 2nd prime
            /*
             * STEP II: Multiply prime numbers to produce a semi-prime
             */

            const semi_prime = p1 * p2;

            /*
             * STEP III: Find LCM of p1 - 1 and p2 - 1
             */

            // get L.C.M. of p1-1 and p2-1
            const lcm = getLCM([p1 - 1, p2 - 1]);

            /*
             * STEP IV: Select a Public Key that is coprime to the LCM
             */

            // pick a random prime (public_key) that lies
            // between 1 and LCM but not a factor of LCM
            const public_key = 313;

            // find 'public_key' complement - private_key - such that
            // (public_key * private_key) % LCM = 1
            //this involves some measure of trial and error
            let i = 1;
            while ((lcm*+ 1) % public_key !== 0) {
                i++;
            }
            /*
             * STEP V: Calculate the Private Key as the inverse of the Public Key.
             */

            const private_key = (* lcm + 1) / public_key;

            const message = "merry xmas";
            let result = encodeWord(message, public_key, semi_prime);
            document.getElementById("word_encrypt").innerHTML += "Message is '" + message + "';<br/>" +
                    "<br/>Publicly encrypted version is [" + result.join(", ") + "]";
            
            result = decodeWord(result, private_key, semi_prime);
            document.getElementById("word_encrypt").innerHTML +=
                    "<br/><br/>Decrypted message is '" + result + "'.";
        </script>

    </body>
</html>


JavaScript Code for Dual Key Encryption - .js

'use strict';

/**
 * Calculates (base^exponent) % modulus using BigInt.
 * Implements the exponentiation by squaring algorithm.
 *
 * @param {BigInt} base The base value.
 * @param {BigInt} exponent The exponent value (must be non-negative).
 * @param {BigInt} modulus The modulus value (must be positive).
 * @returns {BigInt} The result of (base^exponent) % modulus.
 */

function modPow(base, exponent, modulus) {
  if (modulus <= 0n) {
    throw new Error('Modulus must be positive.');
  }
  if (exponent < 0n) {
    // Handling negative exponents requires calculating modular multiplicative inverse
    throw new Error(
      'Negative exponents are not supported by this basic implementation.',
    );
  }

  let result = 1n;
  let b = base % modulus; // Reduce base initially
  let exp = exponent;

  while (exp > 0n) {
    // If the exponent is odd, multiply the result by the current base value
    if (exp % 2n === 1n) {
      result = (result * b) % modulus;
    }
    // Square the base and take the modulo
    b = (* b) % modulus;
    // Halve the exponent (integer division)
    exp = exp / 2n;
  }

  return result;
}

/*
 * STEP VI: Encrypt data
 */

function encodeWord(msg, key, semi_prime) {
  const encryption = [];
  let x;
  for (let i = 0; i < msg.length; i++) {
    // get unicode of this character as x
    x = msg.charCodeAt(i);
    // use RSA to encrypt & save in base 16
    let big_val = modPow(BigInt(x)BigInt(key)BigInt(semi_prime));
    encryption.push(Number(big_val).toString(16));
  }

  return encryption;
}

/*
 * STEP VII: Decrypt data
 */

function decodeWord(code, key, semi_prime) {
  let decryption = '';
  let c;
  for (let i = 0; i < code.length; i++) {
    // use RSA to decrypt
    let x = parseInt(code[i]16);
    c = modPow(BigInt(x)BigInt(key)BigInt(semi_prime));
    decryption += String.fromCharCode(Number(c));
  }

  return decryption;
}





<< PreviousNext >>