Codementor Events

Creating End-to-End Encryption Using Private and Public Key in JavaScript

Published Feb 23, 2023
Creating End-to-End Encryption Using Private and Public Key in JavaScript

Creating End-to-End Encryption Using Private and Public Key in JavaScript

End-to-end encryption is a powerful security measure that ensures that only the intended recipient can access the data. It is a form of encryption that uses two keys, a public key and a private key, to encrypt and decrypt data. In this article, we will look at how to create end-to-end encryption using private and public key in JavaScript.

The first step is to generate a key pair. This can be done using the window.crypto.subtle.generateKey() method. This method takes an object containing the name of the algorithm, the modulus length, the public exponent, and the hash algorithm. The modulus length can be 1024, 2048, or 4096, and the hash algorithm can be SHA-1, SHA-256, SHA-384, or SHA-512.

const { publicKey, privateKey } = await window.crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    modulusLength: 2048, // can be 1024, 2048, or 4096
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
    hash: { name: "SHA-256" }, // can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
  },
  true, // whether the key is extractable (i.e. can be used in exportKey)
  ["encrypt", "decrypt"] // can be any combination of "encrypt" and "decrypt"
);

Once the key pair is generated, the next step is to encrypt the data. This can be done using the window.crypto.subtle.encrypt() method. This method takes an object containing the name of the algorithm, the public key, and the data to be encrypted.

const encryptedData = await window.crypto.subtle.encrypt(
  {
    name: "RSA-OAEP",
  },
  publicKey, // from generateKey or importKey above
  data // ArrayBuffer of data you want to encrypt
);

Finally, the encrypted data can be decrypted using the window.crypto.subtle.decrypt() method. This method takes an object containing the name of the algorithm, the private key, and the encrypted data.

const decryptedData = await window.crypto.subtle.decrypt(
  {
    name: "RSA-OAEP",
  },
  privateKey, // from generateKey or importKey above
  encryptedData // ArrayBuffer of the data
);

In this article, we looked at how to create end-to-end encryption using private and public key in JavaScript, with code examples. We saw how to generate a key pair, encrypt data, and decrypt data. With this knowledge, you can now create secure end-to-end encryption in your JavaScript applications.

Discover and read more posts from Behnam Anjomruz
get started
post commentsBe the first to share your opinion
Atonal Wilson
a year ago

Thank you for Sharing. Very easy to use. Time effective.

Show more replies