Cryptography Basics

Cryptography is the mathematical backbone of trust. In an Operating System, it is used for:

  • Encrypted Filesystems (BitLocker, LUKS).
  • Secure Network Connections (SSH, HTTPS).
  • Code Signing (Preventing malware from loading as a driver).

1. Symmetric Encryption (Shared Secret)

Both parties have the same key.

  • Algorithm: AES (Advanced Encryption Standard).
  • Pros: Extremely fast (Hardware accelerated by AES-NI instructions in CPU).
  • Cons: Key Distribution Problem. How do I send you the key without a hacker intercepting it?

2. Asymmetric Encryption (Public Key)

Each party has a Key Pair.

  • Public Key: Share with everyone. Used to Encrypt.
  • Private Key: Keep secret. Used to Decrypt.
  • Algorithm: RSA, ECC (Elliptic Curve Cryptography).
  • Pros: Solves Key Distribution.
  • Cons: Very slow (1000x slower than AES).
Tip

Hybrid Encryption: In the real world (HTTPS/TLS), we use Asymmetric encryption to securely exchange a Symmetric key. Then we use the Symmetric key for the rest of the conversation.


3. Interactive: Public Key Demo

Alice wants to send a secret to Bob.

Alice
Has Message
"Attack at Dawn"
Bob
Has Keys
Bob-PUB
Bob-PRI
???
Waiting to start...

4. Code Example: AES Encryption

High-performance symmetric encryption.

Go

package main

import (
  "crypto/aes"
  "crypto/cipher"
  "crypto/rand"
  "fmt"
  "io"
)

func main() {
  key := []byte("thisis32bitlongpassphraseimusing") // 32 bytes = AES-256
  text := []byte("My Secret Data")

  // Create Cipher Block
  block, err := aes.NewCipher(key)
  if err != nil { panic(err) }

  // GCM Mode (Galois/Counter Mode) provides encryption + integrity
  aesGCM, err := cipher.NewGCM(block)
  if err != nil { panic(err) }

  // Generate Nonce
  nonce := make([]byte, aesGCM.NonceSize())
  if _, err = io.ReadFull(rand.Reader, nonce); err != nil { panic(err) }

  // Encrypt
  ciphertext := aesGCM.Seal(nonce, nonce, text, nil)
  fmt.Printf("Encrypted: %x\n", ciphertext)
}

Java

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESGCM {
  public static void main(String[] args) throws Exception {
    // Generate Key
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256);
    SecretKey key = keyGen.generateKey();

    // IV (Nonce)
    byte[] iv = new byte[12]; // GCM standard IV size
    new SecureRandom().nextBytes(iv);

    // Encrypt
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    GCMParameterSpec spec = new GCMParameterSpec(128, iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, spec);

    byte[] ciphertext = cipher.doFinal("My Secret Data".getBytes());

    System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(ciphertext));
  }
}