Java Encryption and Decryption: Implementation of Encryption Algorithms

Java Encryption and Decryption: Implementation of Encryption Algorithms

Click the above to follow us!

Java Encryption and Decryption: Implementation of Encryption Algorithms

Want to learn some knowledge about encryption and decryption? Today, let’s talk about encryption and decryption in Java. To be honest, it sounds quite advanced, but it’s not that difficult. Follow my steps, and I guarantee you can master it easily.

Symmetric Encryption: AES Algorithm

What is symmetric encryption? Simply put, it uses the same key for both encryption and decryption. AES (Advanced Encryption Standard) is a common symmetric encryption algorithm. Let’s see how to implement AES encryption in Java:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
public class AESExample {
    public static void main(String[] args) throws Exception {
        // Generate AES key
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // Can be 128, 192, or 256
        SecretKey secretKey = keyGen.generateKey();
        // Encrypt
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal("Hello, World!".getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted: " + encryptedText);
        // Decrypt
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted: " + decryptedText);
    }
}

See, it’s not difficult, right? First, generate a key, then use this key to encrypt and decrypt. The result of the encryption is a bunch of garbled text, so we use Base64 encoding to facilitate transmission and storage.

Friendly reminder: In actual applications, don’t forget to save the key properly, or you won’t be able to decrypt!

Asymmetric Encryption: RSA Algorithm

Asymmetric encryption is different from symmetric encryption; it uses two keys: a public key and a private key. The public key is used for encryption, and the private key is used for decryption; or the private key can be used for encryption and the public key for decryption. RSA is one of the most commonly used asymmetric encryption algorithms.

import java.security.*;
import javax.crypto.Cipher;
import java.util.Base64;
public class RSAExample {
    public static void main(String[] args) throws Exception {
        // Generate RSA key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair pair = keyGen.generateKeyPair();
        PublicKey publicKey = pair.getPublic();
        PrivateKey privateKey = pair.getPrivate();
        // Encrypt
        Cipher encryptCipher = Cipher.getInstance("RSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = encryptCipher.doFinal("Hello, RSA!".getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted: " + encryptedText);
        // Decrypt
        Cipher decryptCipher = Cipher.getInstance("RSA");
        decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted: " + decryptedText);
    }
}

The usage of RSA is quite similar to AES, but it adds the concept of key pairs. The public key can be shared freely, but the private key must be kept secure!

Message Digest: MD5 and SHA

Strictly speaking, MD5 and SHA are not encryption algorithms; they are message digest algorithms. The characteristic of these algorithms is that no matter how long the input is, the output length is fixed, and the original text cannot be derived from it.

import java.security.MessageDigest;
import java.math.BigInteger;
public class DigestExample {
    public static void main(String[] args) throws Exception {
        String input = "Hello, Digest!";
        // MD5
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Bytes = md5.digest(input.getBytes());
        String md5Hex = new BigInteger(1, md5Bytes).toString(16);
        System.out.println("MD5: " + md5Hex);
        // SHA-256
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
        byte[] sha256Bytes = sha256.digest(input.getBytes());
        String sha256Hex = new BigInteger(1, sha256Bytes).toString(16);
        System.out.println("SHA-256: " + sha256Hex);
    }
}

Message digests are commonly used to verify data integrity or store passwords. However, using MD5 to store passwords is no longer secure; it is recommended to use stronger algorithms like bcrypt.

Base64 Encoding

Ultimately, Base64 is not an encryption algorithm but a coding method. It converts binary data into a set of printable characters, commonly used for transmitting binary data over the network.

import java.util.Base64;
public class Base64Example {
    public static void main(String[] args) {
        String originalInput = "Hello, Base64!";
        String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
        System.out.println("Encoded: " + encodedString);
        byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
        String decodedString = new String(decodedBytes);
        System.out.println("Decoded: " + decodedString);
    }
}

The string encoded in Base64 may look like it has been encrypted, but it can be easily decoded. So don’t treat it as an encryption algorithm!

Friendly reminder: When choosing encryption algorithms in actual projects, consider multiple factors such as security, performance, and key management. For sensitive data, it is best to use professional encryption libraries like Bouncy Castle.

Alright, that’s all for today. There’s still a lot to discuss about Java encryption and decryption, such as digital signatures, SSL/TLS, etc. If you’re interested, we can talk about it next time! Remember, learning encryption and decryption is not to do bad things, but to protect data security. When used correctly, this technology can be a great benefit to humanity!

Previous Reviews

Python Natural Language Processing Tool NLTK: 6 Core Functions Explained, Text Analysis Accuracy Improved by 70%!

Batch Compress Images in One Minute, Python Makes Your Website Load Faster

Dask Used by Google Engineers: 5 Big Data Parallel Computing Tips, Processing Speed Improved by 80 Times!

Like and Share

Java Encryption and Decryption: Implementation of Encryption Algorithms

LetMoneyandLoveFlow to You

Leave a Comment