· 8 min read

Locking it Down: Demystifying Encryption, Encoding, and Hashing for Secure Data

In today’s digital age, keeping data secure is a top priority due to rising concerns over privacy and confidentiality. Encryption, encoding, and hashing are three fundamental techniques that are widely used to safeguard data. Unfortunately, people often misuse these terms or confuse them with one another, resulting in a lack of understanding about their intended functions and capabilities. In this blog post, we will delve into the distinctions between encryption, encoding, and hashing and how they are employed to protect sensitive information.

Photo by Markus Spiske on Unsplash

Photo by Markus Spiske on Unsplash

Encryption is the process of converting plaintext into ciphertext, a scrambled and unreadable form, using an encryption algorithm and a key. Encryption is commonly used to protect sensitive information such as credit card numbers, passwords, and other confidential data during transmission or storage. The primary objective of encryption is to provide confidentiality and prevent unauthorized access to the information.

Encryption uses two types of keys: a public key and a private key. Public-key encryption, also known as asymmetric encryption, uses a pair of keys — a public key and a private key. The public key is used to encrypt the plaintext, and the private key is used to decrypt the ciphertext. Private-key encryption, also known as symmetric encryption, uses the same key for both encryption and decryption.

AES (Advanced Encryption Standard) is a commonly used encryption technique that helps keep your data safe and secure. It’s a type of encryption algorithm that uses a secret key to encrypt information, making it difficult for anyone else to read it without the key. Essentially, AES scrambles your data into an indecipherable jumble that can only be unscrambled with the correct key. This makes it an essential tool for safeguarding sensitive information and ensuring that only the intended recipient can access it.

  1. Choose a secret key that will be used to encrypt and decrypt data.
  2. Divide the plaintext into fixed-size blocks.
  3. Apply a series of mathematical transformations to each block of plaintext using the secret key.
  4. Repeat the transformations a fixed number of times (known as rounds).
  5. The result of the final round is the ciphertext.
$key = random_bytes(32);
$plaintext = "Hello, world!";
$iv = random_bytes(16);
$ciphertext = openssl_encrypt(
    $plaintext,
    "AES-256-CBC",
    $key,
    OPENSSL_RAW_DATA,
    $iv
);

echo $decrypted = openssl_decrypt(
    $ciphertext,
    "AES-256-CBC",
    $key,
    OPENSSL_RAW_DATA, 
    $iv
);

In AES encryption, we use a symmetric key algorithm, which means that the same key is used for both encryption and decryption. So, we only need the same key that was used for encryption to decrypt the encrypted data.

This is in contrast to asymmetric key algorithms like RSA (Rivest-Shamir-Adleman), where we use different keys for encryption and decryption. In RSA, the encryption key is public and can be shared with anyone, while the decryption key is kept private. So, anyone can encrypt data using the public key, but only the owner of the private key can decrypt it.

RSA is a popular public-key cryptography algorithm that ensures secure communication and data encryption. Let’s take an example from one of the beloved series “Breaking Bad” to see how RSA can be used to encrypt and decrypt messages shared between two friends.

  1. The first step is to generate a pair of RSA keys — a public key and a private key. The public key can be shared with anyone, while the private key is kept secret. The keys are generated using a software tool, such as OpenSSL.
openssl genpkey -algorithm RSA -out private_key.pem -aes256

openssl rsa -pubout -in private_key.pem -out public_key.pem
  1. Suppose Walter wants to send a confidential message to Jessie. Walter can encrypt the message using Jassie’s public key, which he obtained from Jessie or a public key directory. The encryption process involves converting the plaintext message into a numerical format, applying mathematical operations using Jessie’s public key, and producing a ciphertext that is unreadable without the private key. Only Jessie can decrypt the message using his private key.
  2. Jessie receives the ciphertext and decrypts it using his private key. The decryption process involves applying mathematical operations using the private key and converting the resulting numerical value back into plaintext.
  3. RSA can also be used to create digital signatures that verify the authenticity and integrity of a message. To create a digital signature, the sender applies a mathematical operation using their private key to the message. The recipient can then verify the signature using the sender’s public key. If the signature is valid, the recipient can be confident that the message was sent by the sender and has not been altered in transit.
import * as crypto from 'crypto';
import * as fs from 'fs';

// Load RSA keys from files
const privateKey = fs.readFileSync('private.pem', 'utf-8');
const publicKey = fs.readFileSync('public.pem', 'utf-8');

// The message to be encrypted
const message = 'Hello, Jessie! This is Walter.';

// Encrypt the message using the recipient's public key
const encryptedMessage = crypto.publicEncrypt(publicKey, Buffer.from(message));

// Convert the encrypted message to a string for storage or transmission
const encryptedMessageString = encryptedMessage.toString('base64');

// The recipient decrypts the message using their private key
const decryptedMessage = crypto.privateDecrypt(privateKey, Buffer.from(encryptedMessageString, 'base64'));

// Log the decrypted message
console.log(decryptedMessage.toString());

Other encryption algorithms

  • Blowfish is a symmetric key encryption algorithm that uses block cipher. It is designed to be fast and secure and is used in many applications, including virtual private networks (VPNs) and file encryption.
  • DES (Data Encryption Standard) is a symmetric key encryption algorithm that uses block cipher. It is widely used in banking and other industries to protect sensitive data.
  • AES-GCM (Advanced Encryption Standard — Galois/Counter Mode) is a block cipher mode of operation that combines the Advanced Encryption Standard (AES) with Galois/Counter Mode (GCM) for authentication and integrity.
  • ChaCha20 is a stream cipher that is designed to be fast and secure. It is used in many applications, including Google’s QUIC protocol and the Linux kernel

Encoding is the process of converting data from one form to another, such as from one character set to another or from binary to text. Encoding is not a security measure and does not provide confidentiality or integrity. Instead, it is used to ensure that data can be correctly transmitted and interpreted by different systems and applications.

Some common encoding schemes include ASCII, Unicode, Base64, and URL encoding.

Base64 encoding converts binary data into a text format that can be transmitted over the internet. Here’s how Base64 encoding works:

  1. Take the binary data and divide it into groups of 6 bits.
  2. Convert each 6-bit group into its corresponding Base64 character.
  3. Pad the output with “=” characters as needed to make it a multiple of 4 characters in length.

For example, the binary data “01100110 01101111 01101111” would be converted to “Zm9v” in Base64 encoding.

const str = "Of course it's dangerous, it's very dangerous. That's why I need your help.";
const encodedStr = Buffer.from(str).toString("base64");
console.log(encodedStr);

// output:
// T2YgY291cnNlIGl0J3MgZGFuZ2Vyb3VzLCBpdCdzIHZlcnkgZGFuZ2Vyb3VzLiBUaGF0J3Mgd2h5IEkgbmVlZCB5b3VyIGhlbHAu

Hashing is the process of converting data of any size into a fixed-length value or hash code using a hash function. Hashing is commonly used to ensure the integrity of data, which means that the data has not been tampered with or modified. Hashing is also used for password storage, where the password is hashed and stored instead of storing the plaintext password.

Hashing uses a one-way function, which means that it is not possible to convert the hash code back to the original data. This property makes hashing ideal for password storage since the password is never stored in plaintext form. When a user logs in, the entered password is hashed, and the hash is compared to the stored hash code. If the hashes match — the password is considered valid.

An example of a hashing algorithm is the Secure Hash Algorithm (SHA). SHA is a family of cryptographic hash functions that generate a fixed-size output from any input data.

Here’s an example of how the SHA-256 hashing algorithm works:

  1. Take the input data and divide it into fixed-size blocks.
  2. Apply a series of mathematical operations to each block of data.
  3. Repeat the operations for a fixed number of rounds.
  4. The result of the final round is the hash code.

For example, the input data “moon landing is a hoax” would be hashed using the SHA-256 algorithm to produce the hash code “d9b9f7fd702fe20f13e7f54d2a25c7a4df2b8284b4d71f692e9b7ebf052c131e”

import * as crypto from 'crypto';

function generateSHA256Hash(data: string): string {
  const sha256Hash = crypto.createHash('sha256');
  sha256Hash.update(data);
  return sha256Hash.digest('hex');
}

const data = 'Jesse, look at me. This is our problem, and we need to deal with it together. Like it or not, we\'re in this together.';
const sha256Hash = generateSHA256Hash(data);
console.log(sha256Hash);

Other frequently used hashing algorithms

  • MD5 (Message-Digest algorithm 5) is a widely used hashing algorithm that generates a fixed-length 128-bit hash value.
import * as crypto from 'crypto';

function generateMD5Hash(data: string): string {
  const md5Hash = crypto.createHash('md5');
  md5Hash.update(data);
  return md5Hash.digest('hex');
}

const data = 'Jesse, look at me. This is our problem, and we need to deal with it together. Like it or not, we\'re in this together.';
const md5Hash = generateMD5Hash(data);
console.log(md5Hash);
  • CRC (Cyclic Redundancy Check) is a type of hashing algorithm that is often used for error detection in data transmission.
  • Blake2 is a cryptographic hash function that is faster and more secure than SHA-1 and SHA-2.
  • Whirlpool is a strong hash function that produces a 512-bit hash value.
  • RIPEMD (RACE Integrity Primitives Evaluation Message Digest) is a family of cryptographic hash functions that were developed by a team of European researchers as an alternative to the US-developed SHA algorithms.
  • Tiger is a cryptographic hash function that is designed to be highly secure and efficient.

In conclusion, encryption, encoding, and hashing are three different techniques that serve different purposes in data security. Encryption provides confidentiality, encoding ensures data compatibility, and hashing provides integrity. It is essential to understand the differences between these techniques to use them effectively and ensure that sensitive data is protected.