Java Encryption Algorithms: Principles of Symmetric Encryption, Asymmetric Encryption, and Hash Functions

Java Encryption Algorithms: Principles of Symmetric Encryption, Asymmetric Encryption, and Hash Functions

In modern information technology, data security is a crucial topic. To protect sensitive information, we often need to use various encryption algorithms. This article will detail the three main encryption algorithms in Java: Symmetric Encryption, Asymmetric Encryption, and Hash Functions, along with corresponding code examples.

1. Symmetric Encryption

1.1 Principle

Symmetric encryption is a method of encrypting and decrypting data using the same key. This means that the sender and receiver must share a key to correctly decode the message. Due to its speed and simplicity of implementation, symmetric encryption is commonly used for large-scale data transmission.

1.2 Common Algorithms

  • AES (Advanced Encryption Standard)
  • DES (Data Encryption Standard)

1.3 Java Example Code

Below is an example of symmetric encryption using AES:

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

public class SymmetricEncryption {
    public static void main(String[] args) throws Exception {
        String originalText = "Hello, World!";

        // Generate key
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // Can choose 128, 192, or 256 bit length
        SecretKey secretKey = keyGen.generateKey();

        // Encryption and decryption process
        byte[] encryptedText = encrypt(originalText, secretKey);
        String decryptedText = decrypt(encryptedText, secretKey);

        System.out.println("Original: " + originalText);
        System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(encryptedText));
        System.out.println("Decrypted: " + decryptedText);
    }

    public static byte[] encrypt(String data, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data.getBytes());
    }

    public static String decrypt(byte[] encryptedData, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(encryptedData));
    }
}

2. Asymmetric Encryption

2.1 Principle

Asymmetric encryption uses a pair of public and private keys for secure data transmission. The public key can be shared openly, while the private key must be kept secret. In this method, anyone can use the public key to encrypt a message, but only the person with the corresponding private key can decrypt it.

2.2 Common Algorithms

  • RSA (Rivest-Shamir-Adleman)
  • DSA (Digital Signature Algorithm)

2.3 Java Example Code

Below is an example of asymmetric encryption using RSA:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import javax.crypto.Cipher;

public class AsymmetricEncryption {
    public static void main(String[] args) throws Exception {
        // Create RSA key pair
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        KeyPair pair = generator.generateKeyPair();

        PublicKey publicKey = pair.getPublic();
        PrivateKey privateKey = pair.getPrivate();

        String originalMessage = "Hello RSA!";

        // Encryption and decryption process
        byte[] encryptedMessage = encrypt(originalMessage, publicKey);
        String decryptedMessage = decrypt(encryptedMessage, privateKey);

        System.out.println("Original: " + originalMessage);
        System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(encryptedMessage));
        System.out.println("Decrypted: " + decryptedMessage);
    }

    public static byte[] encrypt(String message, PublicKey pubkey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubkey);
        return cipher.doFinal(message.getBytes());
    }

    public static String decrypt(byte[] messageBytes, PrivateKey privkey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privkey);
        return new String(cipher.doFinal(messageBytes));
    }
}

3. Hash Functions

3.1 Principle

A hash function is a one-way function that converts input data into a fixed-length string, known as a hash value. Unlike traditional “passwords”, hash values cannot be reversed to obtain the original input, making them useful for verifying data integrity, such as storing user passwords.

3.2 Common Algorithms

  • MD5 (Message Digest 5)
  • SHA (Secure Hash Algorithm)

3.3 Java Example Code

Below is an example of calculating a SHA-256 hash value:

import java.security.MessageDigest;

public class HashingExample {
    public static void main(String[] args) throws Exception {
        String inputString = "Hello World";
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        byte[] hash = digest.digest(inputString.getBytes());
        // Convert byte array to hexadecimal string representation
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        System.out.println("Hash value: " + hexString.toString());
    }
}

Conclusion

In this article, we introduced three main types of cryptographic techniques in Java: Symmetric Encryption, Asymmetric Encryption, and Hash Functions. Each method has its unique characteristics and applicable scenarios. In practical applications, one can choose the appropriate method based on the requirements to ensure data security. We hope this content helps you better understand the basic cryptographic concepts in Java.

Leave a Comment