Encryption and Hashing in JavaScript

17 / Sep / 2024 by Mohd Ashraf 0 comments

In today’s digital landscape, the need to secure data is more critical than ever. Whether you’re transmitting sensitive information or storing user credentials, understanding the mechanisms that protect this data is essential. In the world of JavaScript, encryption and hashing are two key techniques that developers can leverage to safeguard information. But what exactly are these processes, and how can you implement them effectively in your JavaScript projects? This blog will take you through the concepts of encryption and hashing, explore their differences, and demonstrate how to apply them in real-world scenarios using JavaScript.

Encryption and hashing are both crucial in securing data, but they serve different purposes and operate differently. Let’s understand these one by one starting with Encryption.

What is Encryption

Encryption acts like a secret code for information. It uses a special process (called an encryption algorithm) along with a key to transform readable data (plaintext) into an unreadable format (ciphertext ). When the intended recipient receives this encrypted data, they use a key to convert it back into its original form.

Encryption

Types of Encryption

  • Symmetric Encryption: This is a cryptographic method that uses the same key for both encryption and decryption.Working of Symmetric Encryption:
    1. Key Generation: The process starts with the creation of a single secret key. This key will be used for both encryption and decryption.
    2. Encryption Process: Using a symmetric encryption algorithm (like AES, DES, or 3DES) and the secret key, the plaintext is converted into an unreadable format. The encrypted data (ciphertext) is then sent to the receiver.
    3. Decryption Process: Using the same symmetric encryption algorithm and key, the receiver decrypts the ciphertext back into its original form.

Symmetric encryption is generally faster than asymmetric encryption, making it ideal for encrypting large amounts of data. However, it has a key distribution problem. To overcome this problem, Asymmetric encryption is often preferred in some specific scenarios.

Symmetric Encryption

  • Asymmetric Encryption: Unlike symmetric encryption, which uses the same key for both processes, asymmetric encryption uses two mathematically related distinct keys: a public key for encryption and a private key for decryption. Working of Asymmetric Encryption is the same as of symmetric encryption, the only difference is two different keys are used.

Asymmetric Encryption

Use cases of Encryption

  • Secure Online Communication (HTTPS): Encryption is used to safeguard data such as usernames, passwords, or payment details while transmitting it over a network. HTTPS (SSL/TLS) encrypts communication between web browsers and servers, ensuring that data remains secure.
  • Email Encryption:  Encrypting email content to ensure that only the intended recipient can read the message. PGP (Pretty Good Privacy) or S/MIME (Secure/Multipurpose Internet Mail Extensions) are used to encrypt emails.
  • Encrypted Messaging Apps: End-to-end encryption (E2EE) is used in messaging apps to ensure that only the sender and the receiver can read the messages. Apps like WhatsApp, Signal, and Telegram use end-to-end encryption.

So far, you’ve learned about encryption and its use cases. However, you might have noticed that Encryption is a key-based method and a reversible process which means that you can get the original data using the decryption key, and if an attacker gains access to the key, they can decrypt the data.

To address the issue of data reversibility, we have a method called hashing, which is irreversible. While encryption and hashing serve different purposes, and neither is inherently superior to the other, they are used in distinct scenarios. For instance, if you send a large text message over WhatsApp, hashing wouldn’t be suitable because the message needs to be decrypted later by the recipient.

Let’s see Asymmetric Encryption implementation in ReactJS/NextJS and Node.js using node-forge package.

Asymmetric encryption server-side implementation

This one is the app.js file in the root folder, wherein line 11 you can see Encryption file import, and in line 36 route establishment with JWT authentication.

Asymmetric encryption server-side implementation

Encryption file in the router folder where you can see the node-forge package is imported in line 2, public and private key generation on line 5 and three subsequent endpoints.

Asymmetric encryption server-side implementation

Authentication happens here in the index.js file inside the middleware folder.

Now moving towards client-side.

Asymmetric encryption client-side implementation

Asymmetric encryption client-side implementation

Here you can clearly see an useEffect where we are fetching the public key for the encryption process. After that we have 2 methods, one for encryption and another for decryption and finally a console to log data.

Asymmetric Encryption console output

In the above example, you may be wondering why we don’t have an endpoint for the private key, so the answer is very simple: the private key is meant to be kept secret. Exposing it can compromise the security of the encryption and decryption process. In a production environment, private keys should remain on the server and never be sent to or stored on the client side.

Now, the question is when to use encryption versus hashing. This will become clearer in the upcoming sections. For now, it’s important to first understand what hashing is and how it works.

What is Hashing

Hashing is a process that converts input data of any size into a fixed-size string of characters. Secure Hash Algorithm (SHA) is a renowned hash function that takes an input and returns a fixed-size string, typically a hash digest represented in hexadecimal.

You may be wondering, can hashing be cracked or decrypted? Hashing is similar to encryption, the only difference between hashing and encryption is that hashing is one-way, meaning once the data is hashed, the resulting hash digest cannot be cracked unless a Brute force attack or Rainbow table attack is used.

Let’s take an example to understand it better. Suppose we have two slightly different inputs ‘Hello’ and ‘hello’, hashed with SHA-256 function. The hash digest of the first message will look like

"185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969"

while for the second message it will-

"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

This is referred to as the avalanche effect. This effect is important in cryptography, as it means even the slightest change in the input message completely changes the output. This will stop attackers from being able to understand what the hash digest originally said and tell the receiver of the message whether or not the message has been changed while in transit.

Hashing

Types of SHA

SHA-1 was released in 1995 with a 160-bit hash length and was widely used in the past for digital signatures and SSL certificates. However, due to the short length of the hash digest, SHA-1 is more easily brute-forced and it can also give the same hash digest to two different values (known as collision), it is no longer considered secure and deprecated for cryptographic purposes.

SHA-2 was released in 2001 with a variety of bit lengths from 256 to 512.

  • SHA-224: hash digest of 224 bits
  • SHA-256: hash digest of 256 bits (64 hex characters)
  • SHA-384: hash digest of 384 bits
  • SHA-512: hash digest of 512 bits

SHA-2 is widely used and is considered secure for most cryptographic purposes. It has been used in all SSL certificates, digital signatures, and blockchain technologies since 2016.

SHA-3 was released in 2015 and developed as a backup in case vulnerabilities were found in SHA-2. It uses a different internal structure (Keccak algorithm) and provides additional security. While SHA-2 remains secure and widely used, SHA-3 offers an alternative for higher levels of security.

In modern cryptography, SHA-2 and SHA-3 are the preferred.

Currently, SHA-2 is the industry standard for hashing algorithms. However, SHA-3 may eventually take its place. As SHA-2 becomes outdated or vulnerable, a shift to SHA-3 is likely in the future.

SHA-256 method

calling sha256 method

SHA-256 console output

Now, you have a strong understanding of what Encryption and Hashing are and how they differ from each other. Before concluding the blog let’s see some use cases of Hashing.

Use cases of Hashing

The most important use case of Hashing is to hash a password. Also, SHAs are essential not only for digital signatures and certificates in SSL/TLS connections, as mentioned earlier, but also play a crucial role in other applications. SHAs are used in protocols such as SSH, S/MIME (Secure/Multipurpose Internet Mail Extensions), and IPSec.

  • Hashing is used in checksums to detect errors in data transmission. Protocols like TCP/IP use checksums to verify the integrity of data packets transmitted over the internet.
  • Hashing is used in version control systems (e.g., Git) to create unique identifiers (hashes) for each commit. Git uses SHA-1 (and moving towards SHA-256) to generate commit hashes, which track changes in the project history.
  • Hashing is used in blockchains to link blocks and ensure the immutability of the chain. Bitcoin and other cryptocurrencies use SHA-256 hashing to maintain the integrity of the blockchain and ensure the security of transactions.

Conclusion

Encryption ensures that sensitive data remains confidential, allowing for secure transmission and storage of information. On the other hand, hashing provides integrity and authenticity, making sure that data is neither tampered with nor easily reversed.

By leveraging these techniques, you can ensure your applications remain secure, protecting both users and sensitive data from evolving threats. As the need for security grows, staying informed and adopting best practices in encryption and hashing will continue to be essential for JavaScript developers.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *