Cryptography and Secure Coding Practices

Cryptography is the practice of securing data through encryption and decryption. Java provides robust cryptographic APIs within the javax.crypto and java.security packages, enabling developers to implement secure data transmission, authentication, and integrity checks.

Key Concepts in Cryptography:

  • Encryption: Converting plaintext data into an unreadable format (ciphertext).
  • Decryption: Reversing the encryption process to obtain the original data.
  • Hashing: Generating a fixed-length string from data to verify integrity.
  • Digital Signatures: Verifying data authenticity and integrity using keys.
  • Key Management: Safeguarding encryption keys from unauthorized access.

Common Cryptography APIs in Java

Encryption and Decryption Example 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 AESEncryptionDemo {
    public static void main(String[] args) throws Exception {
        String data = "Confidential Data";

        // Generate a key
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // AES key size: 128 bits
        SecretKey secretKey = keyGen.generateKey();

        // Encrypt the data
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedData);
        System.out.println("Encrypted Data: " + encryptedText);

        // Decrypt the data
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedData);
        System.out.println("Decrypted Data: " + decryptedText);
    }
}
/*
Encrypted Data: ajdks9hs92lsj... (random ciphertext)
Decrypted Data: Confidential Data
*/

Secure Hashing Using SHA-256:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class HashingDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter data to hash:");
        String data = scanner.nextLine();

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(data.getBytes());
            StringBuilder hexString = new StringBuilder();

            for (byte b : hash) {
                hexString.append(String.format("%02x", b));
            }

            System.out.println("Hashed Data (SHA-256): " + hexString.toString());

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
/*
Enter data to hash:
password123
Hashed Data (SHA-256): ef92b778bae... (hashed value)
*/

Java provides comprehensive cryptographic APIs that facilitate encryption, decryption, hashing, and secure key management. Implementing secure coding practices such as strong encryption algorithms, secure key storage, and proper exception handling is essential for protecting sensitive data and maintaining data integrity in Java applications.

Scroll to Top