DEV Community

Repana Reddy Sekhar
Repana Reddy Sekhar

Posted on

Encryption vs Hashing 🤔 Lets decode

Everyone thinks encryption and hashing are same, but there is so much difference between them which we will see next.

While both techniques are essential for protecting data, they serve distinct purposes. In this post, we'll delve into the disparities between encryption and hashing, exploring their applications and providing practical code examples.

Encryption:

Encryption is a process that transforms readable data into an unreadable format, commonly known as ciphertext. This conversion is reversible, meaning that the ciphertext can be decrypted back into the original plaintext if the proper key is available. Encryption is commonly used to secure data during transmission or storage.

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class EncryptionExample {

    private static final String secretKey = "MySecretKey123"; // Replace with a strong and secure key

    public static void main(String[] args) {
        // Original data
        String originalData = "Sensitive information";

        // Encryption example using AES algorithm
        String encryptedData = encrypt(originalData);
        System.out.println("Original data: " + originalData);
        System.out.println("Encrypted data: " + encryptedData);

        // Decryption example
        String decryptedData = decrypt(encryptedData);
        System.out.println("Decrypted data: " + decryptedData);
    }

    private static String encrypt(String data) {
        try {
            // Generate a key specification from the secret key
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");

            // Create a Cipher instance with AES algorithm
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

            // Encrypt the data
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());

            // Encode the encrypted data using Base64
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String decrypt(String encryptedData) {
        try {
            // Generate a key specification from the secret key
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");

            // Create a Cipher instance with AES algorithm
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

            // Decode the Base64 encoded encrypted data
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);

            // Decrypt the data
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            // Convert the decrypted bytes to a string
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Remember to replace the secretKey in the EncryptionExample program with a strong and secure key. The decrypt function in this program demonstrates the decryption process using the same key used for encryption.

Hashing:

Hashing is a one-way process that converts input data into a fixed-size string of characters, commonly referred to as a hash or digest. Unlike encryption, hashing is not reversible, meaning that you cannot retrieve the original data from its hash. Hashing is frequently employed for data integrity verification and password storage.

import java.security.MessageDigest;

public class HashingExample {

    public static void main(String[] args) {
        // Original data
        String originalData = "Sensitive information";

        // Hashing example using SHA-256 algorithm
        String hashedData = hash(originalData);
        System.out.println("Original data: " + originalData);
        System.out.println("Hashed data: " + hashedData);
    }

    private static String hash(String data) {
        try {
            // Create a MessageDigest instance with SHA-256 algorithm
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // Update the digest with the data bytes
            byte[] hashedBytes = digest.digest(data.getBytes());

            // Convert the hashed bytes to a hexadecimal representation
            StringBuilder hexStringBuilder = new StringBuilder();
            for (byte hashedByte : hashedBytes) {
                hexStringBuilder.append(String.format("%02x", hashedByte));
            }

            return hexStringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Summary: Encryption ensures confidentiality by transforming data into a reversible format, while hashing provides data integrity and password protection through irreversible processes. Understanding when and how to use each technique is crucial for implementing robust security measures in applications and systems.

Happy coding!

Feel free like this blog and subscribe for more tech blogs.
Feel free to buy me a coffee: https://ko-fi.com/repanareddysekhar

Top comments (0)