Mastering Cryptography: From Classic Ciphers to Java Implementations

This article demystifies cryptography by explaining fundamental concepts, tracing its history from ancient substitution ciphers to modern symmetric and asymmetric algorithms, and providing complete Java code examples for DES, AES, RSA, signing, verification, and hashing techniques.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Cryptography: From Classic Ciphers to Java Implementations

The Smoke‑Free Battlefield – An Overview of Cryptography

Without a solid foundation you may build a small hut, but you cannot construct a sturdy mansion.

Many developers encounter terms such as MD5, SHA, DES, AES, RSA, public‑key encryption, private‑key decryption, signing and verification and wonder what they actually mean. Although these concepts may seem distant, they become essential when designing external APIs or security‑critical systems.

In everyday life cryptography is already at work – for example, the tongue‑twister in the Chinese drama "Sleeping on My Upper Bunk" can be seen as a simple substitution cipher.

Fundamental Terminology

Plaintext : the original, unencrypted data.

Encryption method : the rule used to transform plaintext.

Ciphertext : the result of applying the encryption method; it can be transmitted publicly.

Key : the decisive factor in the encryption method, which may be a number, word, or a combination of characters.

To recover the original message, the receiver must know both the encryption method and the key.

Historical Overview

Classical Cryptography

Cryptographic techniques date back to around 1900 BC in ancient Egypt, where special symbols and simple substitution were used. A 1500 BC Babylonian clay tablet records a secret recipe. The Greeks invented steganography (e.g., writing with milk or covering text with wax). The Romans employed the Caesar cipher, shifting letters by a fixed offset (e.g., offset 3 maps A→D, B→E).

Caesar cipher illustration
Caesar cipher illustration

Modern Cryptography

The modern era began with the need to protect military radio communications during World Wars. Marconi’s trans‑Atlantic wireless experiment (1901) highlighted the vulnerability of broadcast signals, prompting the development of encryption techniques. Notable milestones include the British decryption of the Zimmermann telegram (1917), the breaking of the German Enigma machine (1939‑1941), Shannon’s 1945 “A Mathematical Theory of Cryptography” linking cryptography to information theory, the adoption of DES as a federal standard in 1977, and the introduction of public‑key cryptography (Diffie‑Hellman, 1976) which eliminated the need for pre‑shared keys.

Symmetric Encryption

Symmetric encryption uses the same secret key for both encryption and decryption. Common algorithms are DES, 3DES, Blowfish, RC5, IDEA, and the widely used AES.

Advantages: public algorithm, low computational cost, fast processing. Disadvantages: key distribution and management are difficult; each pair of communicating parties needs a unique secret key.

Encryption process:

Encryption: plaintext + key = ciphertext Decryption:

ciphertext - key = plaintext
Symmetric encryption diagram
Symmetric encryption diagram

DES Implementation in Java

private static final String DES = "DES";

public static void main(String[] args) throws Exception {
    String data = "123 456";
    String key = "wang!@#$";
    System.err.println(encrypt(data, key));
    System.err.println(decrypt(encrypt(data, key), key));
}

public static String encrypt(String data, String key) throws Exception {
    byte[] bt = encrypt(data.getBytes(), key.getBytes());
    return new BASE64Encoder().encode(bt);
}

public static String decrypt(String data, String key) throws IOException, Exception {
    if (data == null) return null;
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] buf = decoder.decodeBuffer(data);
    byte[] bt = decrypt(buf, key.getBytes());
    return new String(bt);
}

private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
    SecureRandom sr = new SecureRandom();
    DESKeySpec dks = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    Cipher cipher = Cipher.getInstance(DES);
    cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
    return cipher.doFinal(data);
}

private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
    SecureRandom sr = new SecureRandom();
    DESKeySpec dks = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    Cipher cipher = Cipher.getInstance(DES);
    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
    return cipher.doFinal(data);
}

Key notes for DES in Java:

The key length must be at least 8 bytes.

If the key is longer than 8 bytes, only the first 8 bytes are used (see DESKeySpec implementation).

Advanced Symmetric Algorithms – AES

AES (Advanced Encryption Standard) is a symmetric block cipher with key sizes of 128, 192, or 256 bits and a fixed block size of 128 bits. It replaces DES and is widely adopted by governments and industry.

Java’s Cryptography Extension (JCE) provides the Cipher class for encryption/decryption. The transformation string follows the format algorithm/mode/padding (e.g., AES/ECB/PKCS5Padding). If omitted, the default mode is ECB and the default padding is PKCS5Padding.

public static void main(String[] args) throws Exception {
    String key = "1234567890123456"; // 16‑byte key for AES‑128‑ECB
    String src = "buxuewushu";
    System.out.println(src);
    String encrypted = Encrypt(src, key);
    System.out.println("Encrypted: " + encrypted);
    String decrypted = Decrypt(encrypted, key);
    System.out.println("Decrypted: " + decrypted);
}

public static String Encrypt(String sSrc, String sKey) throws Exception {
    if (sKey == null) { System.out.print("Key is null"); return null; }
    if (sKey.length() != 16) { System.out.print("Key length is not 16"); return null; }
    byte[] raw = sKey.getBytes("utf-8");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
    return new Base64().encodeToString(encrypted);
}

public static String Decrypt(String sSrc, String sKey) throws Exception {
    try {
        if (sKey == null) { System.out.print("Key is null"); return null; }
        if (sKey.length() != 16) { System.out.print("Key length is not 16"); return null; }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] encrypted1 = new Base64().decode(sSrc);
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original, "utf-8");
    } catch (Exception e) { System.out.println(e.toString()); return null; }
}

Asymmetric Encryption – RSA

RSA uses a pair of keys: a public key for encryption (or signature verification) and a private key for decryption (or signing). It enables secure communication without prior key exchange and provides digital signatures.

Key Pair Generation

public static KeyPair buildKeyPair() throws NoSuchAlgorithmException {
    final int keySize = 2048;
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keySize);
    return keyPairGenerator.genKeyPair();
}

Encryption / Decryption

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

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

Signing / Verification

private static String signWithRSA(String content, PrivateKey privateKey) throws Exception {
    Signature signature = Signature.getInstance("SHA1WithRSA");
    signature.initSign(privateKey);
    signature.update(content.getBytes("utf-8"));
    return base64Encode(signature.sign());
}

private static boolean checkSignWithRSA(String content, PublicKey publicKey, String sign) throws Exception {
    Signature signature = Signature.getInstance("SHA1WithRSA");
    signature.initVerify(publicKey);
    signature.update(content.getBytes("utf-8"));
    return signature.verify(base64Decode(sign));
}

Example usage prints encrypted data, decrypted data, generated signature, and verification result (true).

Hash (Message Digest) Algorithms

Hash algorithms produce a fixed‑length fingerprint of arbitrary input without using a key. They are irreversible and are essential for data integrity, digital signatures, and password storage.

Common families include CRC (8/16/32), MD2/MD4/MD5, SHA‑1/256/384/512, RIPEMD, PANAMA, TIGER, ADLER32, etc. Good hash functions exhibit collision resistance, pre‑image resistance, and fixed output length.

MD5 Example in Java

public static String getMD5Str(String str) throws Exception {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());
        return new BigInteger(1, md.digest()).toString(16);
    } catch (Exception e) {
        throw new Exception("MD5 encryption error, " + e.toString());
    }
}

References and source code are available at https://github.com/modouxiansheng/Doraemon .

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SecurityHashing
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.