Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series — Extended Module 17 - Advanced and Post Quantum Cryptography

Java Program for Learning with Errors LWE Cryptography

Reviewed & accurate
AI Summary

Introduction

Oded Regev introduced Learning With Errors (LWE) in his 2005 paper "On Lattices, Learning with Errors, Random Linear Equations, and the Construction of Quantum Safe Cryptographic Primitives", awarded the Godel Prize in 2018. LWE is the foundation of post-quantum cryptography: an encryption scheme whose security reduces to worst-case lattice problems that are believed hard even for quantum computers. The NIST Post-Quantum Cryptography standardization process selected Kyber (an LWE-based key encapsulation) as the FIPS 203 standard in 2024.

For Java learners, LWE is the simplest cryptosystem whose security is conjectured post-quantum. The mathematics is just linear algebra modulo a prime q with small additive noise. The encryption scheme fits in 80 lines of Java with no BigInteger needed, but it scales to cryptographic security at parameter sizes around q=3329, n=512.

What is Learning With Errors?

LWE is a public-key encryption scheme in the lattice-cryptography family. The setup is a prime modulus q, a secret dimension n, and a number of public samples m. The private key is a secret vector s in Z_q^n. The public key is m samples (a_i, b_i) where each a_i is uniformly random in Z_q^n and b_i = a_i . s + e_i mod q with e_i a small noise term (e.g., from a discrete Gaussian or a small uniform range). Encryption of a single bit b is the sum of selected (a_i, b_i) values with the bit added to the b-sum offset by q/2.

The scheme is unique because the security reduces to worst-case lattice problems (GapSVP and SIVP) via Regev's quantum reduction. Even a quantum computer cannot break LWE in polynomial time unless it can solve worst-case lattice problems. This makes LWE the leading candidate for post-quantum standardization.

How LWE Works - Step by Step

Step 1: Key generation. Pick a prime q (e.g., 13 for demo, 3329 for Kyber), a secret dimension n (e.g., 3 for demo, 256 for Kyber), and a sample count m (e.g., 5 for demo, k*n for Kyber). Pick the secret s uniformly in Z_q^n. Generate m random a_i in Z_q^n and m small noise terms e_i. Compute b_i = a_i . s + e_i mod q. The public key is (a_1, b_1, ..., a_m, b_m); the private key is s.

Step 2: Encryption. To encrypt a bit b, pick a random binary vector r in {0, 1}^m. Compute the ciphertext c1 = sum of a_i over i with r_i = 1 (a vector in Z_q^n) and c2 = sum of b_i over i with r_i = 1, plus (q/2) * b. The intuition is that c1 . s = sum of (a_i . s) over r_i = 1, and c2 contains the same sum (with noise) plus the bit scaled by q/2.

Step 3: Decryption. Compute v = c2 - c1 . s mod q. This equals (sum of e_i over r_i = 1) + (q/2) * b mod q. Since the noise terms are small, v is close to 0 (for b=0) or close to q/2 (for b=1). Round v to the nearest of {0, q/2}; if closer to q/2, output 1, else 0.

Step 4: Security argument. The LWE assumption states that the distribution of (a_i, b_i) is computationally indistinguishable from uniform when s is uniform and the noise is small. Under this assumption, an attacker cannot extract information about r (and hence about b) from the ciphertext. The construction is semantically secure (IND-CPA) under LWE.

Java Program for Learning with Errors LWE Cryptography

import java.util.Arrays;

public class LweCryptographyDemo {

    static final int Q = 13; // prime modulus
    static final int N = 3;  // secret dimension
    static final int M = 5;  // number of public samples

    // Demo secret vector
    static final int[] S = {1, 2, 3};

    // Demo public samples (a_i, b_i = a_i.s + e_i mod q)
    static final int[][] A = {
        {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}, {1, 1, 1}
    };
    static final int[] E = {1, 1, 0, 1, -1}; // small noise
    static final int[] B;

    static {
        B = new int[M];
        for (int i = 0; i < M; i++) {
            int dot = 0;
            for (int j = 0; j < N; j++) {
                dot += A[i][j] * S[j];
            }
            B[i] = ((dot + E[i]) % Q + Q) % Q;
        }
    }

    // Encrypt bit using a random subset r in {0,1}^M
    public static int[] encryptBit(int bit, int[] r) {
        int[] c1 = new int[N];
        int c2 = 0;
        for (int i = 0; i < M; i++) {
            if (r[i] == 1) {
                for (int j = 0; j < N; j++) {
                    c1[j] = (c1[j] + A[i][j]) % Q;
                }
                c2 = (c2 + B[i]) % Q;
            }
        }
        if (bit == 1) {
            c2 = (c2 + Q / 2) % Q; // add q/2 = 6
        }
        return new int[]{c1[0], c1[1], c1[2], c2};
    }

    // Decrypt: compute c2 - c1.s mod q, round to nearest of {0, q/2}
    public static int decryptBit(int[] c) {
        int dot = 0;
        for (int j = 0; j < N; j++) {
            dot += c[j] * S[j];
        }
        int v = ((c[3] - dot) % Q + Q) % Q;
        int dist0 = Math.min(v, Q - v);
        int distHalf = Math.min(Math.abs(v - Q / 2), Q - Math.abs(v - Q / 2));
        return (distHalf < dist0) ? 1 : 0;
    }

    public static void main(String[] args) {
        System.out.println("Setup: q=" + Q + " n=" + N + " m=" + M);
        System.out.println("Secret s = (" + S[0] + ", " + S[1]
            + ", " + S[2] + ")");
        System.out.println("Public samples (a_i, b_i):");
        for (int i = 0; i < M; i++) {
            System.out.println("  a_" + i + " = (" + A[i][0] + ", "
                + A[i][1] + ", " + A[i][2] + "), b_" + i + " = " + B[i]);
        }

        // Encrypt and decrypt bit 0 and 1 with the same r
        int[] r = {1, 1, 0, 0, 1};
        for (int bit = 0; bit < 2; bit++) {
            int[] c = encryptBit(bit, r);
            int d = decryptBit(c);
            System.out.println("bit=" + bit + " -> c=(" + c[0] + ","
                + c[1] + "," + c[2] + "," + c[3] + ") -> decrypt=" + d);
        }

        // Try multiple random subsets for bit=1
        int[][] subsets = {
            {1, 1, 0, 0, 1}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}
        };
        for (int t = 0; t < subsets.length; t++) {
            int[] c = encryptBit(1, subsets[t]);
            int d = decryptBit(c);
            System.out.println("trial " + t + ": bit=1, r="
                + Arrays.toString(subsets[t]) + ", decrypt=" + d);
        }
    }
}

Code Explanation - Line by Line

The constants Q, N, M encode the demo parameters. Q=13 is a small prime modulus. N=3 is the secret dimension (the secret vector s has 3 components). M=5 is the number of public samples. In Kyber-768 (FIPS 203), the corresponding parameters are q=3329, n=256, m=768.

The S, A, E arrays encode the demo secret, public samples, and noise. S=(1,2,3) is the secret vector. Each row of A is a public a_i. E contains small noise terms from {-1, 0, 1}. B is computed in the static initializer: B[i] = A[i] . S + E[i] mod Q.

The encryptBit method picks a binary subset r, sums the corresponding a_i into c1 and b_i into c2, and adds Q/2 to c2 if bit=1. The intuition is that c1 . s = sum of (a_i . s) = sum of (b_i - e_i) = (sum of b_i) - (sum of e_i), so c2 - c1 . s = (sum of e_i) + bit * (Q/2). The noise terms are small, so the result is close to 0 (for bit=0) or close to Q/2 (for bit=1).

The decryptBit method computes v = (c2 - c1.s) mod Q and rounds it to the nearest of {0, Q/2}. The Math.min(v, Q-v) trick computes the cyclic distance to 0; the Math.abs(v - Q/2) trick computes the cyclic distance to Q/2. The smaller distance wins.

The main method demonstrates three things: print the public samples; encrypt and decrypt bit 0 and bit 1 with the same r to verify round-trip correctness; encrypt bit 1 with three different r values to demonstrate that the encryption is probabilistic and decryption succeeds regardless of r.

Sample Input and Output

Setup: q=13 n=3 m=5
Secret s = (1, 2, 3)
Public samples (a_i, b_i):
  a_0 = (1, 0, 0), b_0 = 2
  a_1 = (0, 1, 0), b_1 = 3
  a_2 = (0, 0, 1), b_2 = 3
  a_3 = (1, 1, 0), b_3 = 4
  a_4 = (1, 1, 1), b_4 = 5
bit=0 -> c=(2,2,1,10) -> decrypt=0
bit=1 -> c=(2,2,1,3) -> decrypt=1
trial 0: bit=1, r=[1, 1, 0, 0, 1], decrypt=1
trial 1: bit=1, r=[1, 0, 1, 0, 1], decrypt=1
trial 2: bit=1, r=[0, 1, 0, 1, 0], decrypt=1

The output confirms that both bits decrypt correctly with the same r, and three different r values all encrypt and decrypt bit 1 correctly. The cyclic-distance rounding handles noise gracefully.

Common Mistakes to Avoid

1. Picking noise terms that are too large. If e_i can be larger than q/4, decryption will sometimes round to the wrong value. The standard choice is noise bounded by q/4 in absolute value; Kyber uses a centered binomial distribution with standard deviation roughly q/16.

2. Forgetting to reduce mod q at every step. Without mod-q reduction, the intermediate sums grow linearly in m, eventually overflowing int (for the demo) or becoming computationally expensive (for production with BigInteger). Always reduce mod q after each addition or multiplication.

3. Using a non-prime q. LWE security relies on Z_q being a field (so q must be prime). With composite q, the analysis breaks down and the scheme may be insecure. Kyber uses q = 3329 = 2^11 - 2^6 - 2^4 - 2^3 + 1, a prime specifically chosen for efficient NTT.

4. Reusing r across encryptions. The randomness r is part of the encryption; reusing it leaks the relationship between two ciphertexts and may reveal the bit. Always sample r freshly per encryption using a cryptographic random number generator.

Real-World Applications

The NIST Post-Quantum Cryptography standardization process selected Kyber (an LWE variant called Module-LWE) as the FIPS 203 standard for key encapsulation in 2024. Kyber is being deployed in TLS 1.3 via the X25519Kyber768Draft00 hybrid KEM, used in production by Chrome, Cloudflare, and AWS to protect against future quantum adversaries.

The FIPS 204 standard (Dilithium) for post-quantum signatures is based on Module-LWE as well. Dilithium signatures are roughly 2.7 KB, much larger than Ed25519's 64 bytes but conjectured secure against quantum attacks.

Homomorphic encryption schemes BGV (Brakerski-Gentry-Vaikuntanathan) and BFV (Brakerski-Fan-Vercauteren) are built on LWE and Ring-LWE. These schemes support arbitrary-depth arithmetic circuits on encrypted data and are used in privacy-preserving machine learning, encrypted databases, and private set intersection.

Fully homomorphic encryption (FHE) libraries like Microsoft SEAL, IBM HELIB, and Zama CONCRETE all implement LWE-based schemes. Real-world applications include privacy-preserving medical AI inference, encrypted search, and confidential cloud computing where the cloud never sees the plaintext.

Conclusion

LWE is the foundation of post-quantum public-key cryptography, combining linear-algebra simplicity with conjectured quantum resistance. Our Java program demonstrated key generation, bit encryption, decryption via rounding, and the probabilistic property. Next study Ring-LWE (the polynomial-ring variant that powers Kyber), Module-LWE (the variant in FIPS 203), and fully homomorphic encryption schemes like BGV and CKKS.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments