Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Hashing vs Encryption - OWASP Top 10

1. Introduction

In the realm of cybersecurity, understanding the difference between hashing and encryption is crucial. Both are cryptographic techniques used to protect sensitive data, but they serve different purposes.

2. Hashing

What is Hashing?

Hashing is a one-way function that converts data of any size into a fixed-size string of text, typically a digest. It is primarily used for data integrity verification.

Important Note: Hashing is irreversible. Once data is hashed, it cannot be converted back to its original form.

Common Hashing Algorithms

  • MD5
  • SHA-1
  • SHA-256
  • SHA-3

Code Example


import hashlib

# Hashing a password
password = "mysecretpassword"
hashed_password = hashlib.sha256(password.encode()).hexdigest()
print("Hashed Password:", hashed_password)
                

3. Encryption

What is Encryption?

Encryption is a two-way function that transforms data into a format that cannot be read without a decryption key. It is used to protect data confidentiality.

Important Note: Encryption can be reversed if the correct key is available.

Common Encryption Algorithms

  • AES (Advanced Encryption Standard)
  • RSA (Rivest-Shamir-Adleman)
  • DES (Data Encryption Standard)

Code Example


from Crypto.Cipher import AES
import os

# Encryption
key = os.urandom(16)  # AES key
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
plaintext = b"Secret Message"
ciphertext, tag = cipher.encrypt_and_digest(plaintext)

print("Ciphertext:", ciphertext)
                

4. Key Differences Between Hashing and Encryption

  1. Purpose: Hashing is used for data integrity, while encryption is used for data confidentiality.
  2. Reversibility: Hashing is irreversible; encryption can be reversed with the correct key.
  3. Output Size: Hashing produces a fixed-size output; encryption's output size depends on input size.
  4. Use Cases: Hashing is used for password storage; encryption is used for secure data transmission.

5. Best Practices

  • Use strong, well-established algorithms (e.g., SHA-256 for hashing, AES for encryption).
  • Implement salting with hashes to prevent rainbow table attacks.
  • Store encryption keys securely and separate from encrypted data.
  • Regularly update and patch cryptographic libraries.

6. FAQ

What is a salt in hashing?

A salt is a random value added to the input of a hash function to ensure that identical inputs do not result in identical hashes.

Can I use hashing for storing sensitive information?

Yes, but hashing is suitable mainly for passwords. For sensitive information that needs to be readable, use encryption.

Is encryption always better than hashing?

Not necessarily. The choice between hashing and encryption depends on the use case. Use hashing for integrity and encryption for confidentiality.