Asymmetric Cryptography: From RSA to Elliptic Curves
Learn the intuition, mathematics, algorithms and security trade-offs of public-key encryption, digital signatures and key agreement. Start with small numbers, then explore the variants that appear in cryptographic research and standards.
18 algorithms and algorithm families8 interactive laboratoriesWorked examplesSelf-check quizOffline, single-file HTML
Public-key cryptography uses mathematical operations that are easy to compute in one direction but difficult to reverse without special information. It underpins secure communications, identity verification, digital signatures and privacy-preserving computation.
1. Build an intuition
Read the plain-language descriptions and the short step-by-step process for each algorithm.
2. Inspect the mathematics
Open the deeper technical sections for formulas, assumptions, variants and implementation issues.
3. Try it yourself
Change inputs in the eight laboratories. Every result is computed locally with JavaScript big integers.
Teaching examples are intentionally insecure.The laboratories use tiny primes, simplified encodings and textbook arithmetic to make each mechanism visible. They are not production implementations. Never use their outputs as real keys or deploy them to protect information.
The original version of this page introduced Diffie-Hellman, RSA, ElGamal, MQV and Rabin. This expanded version retains those topics, corrects an important oversimplification about Rabin decryption and adds RSA variants, homomorphic cryptosystems, password-authenticated key exchange and a complete elliptic-curve section.
Chapter 2 / The mental model
Three different jobs, not one
Public-key encryption
Anyone can encrypt using the recipient's public key. Only the corresponding private key should decrypt. Examples: RSA-OAEP, ElGamal-derived schemes and Paillier.
Digital signatures
The signer uses a private key; others verify with the public key. A signature does not hide the message. Examples: RSA-PSS, ECDSA and Ed25519.
Key establishment
Parties produce a shared secret and derive symmetric encryption keys. Diffie-Hellman, ECDH, MQV and SPEKE are key-establishment protocols, not general-purpose message ciphers.
In a real application, an authenticated key exchange or key-encapsulation mechanism normally establishes a shared secret; a key derivation function (KDF) transforms it into keys; and an authenticated symmetric cipher, such as AES-GCM, encrypts the actual data. This is called hybrid encryption.
Chapter 3 / Mathematics without mysticism
Five ideas that make the algorithms understandable
Modular arithmetic.17 mod 5 = 2 means 17 and 2 leave the same remainder after division by 5. Cryptographic computations are repeatedly reduced modulo a large number.
Exponentiation.5^3 mod 23 = 10. Large modular powers can be computed efficiently by repeated squaring without expanding the entire power.
Prime numbers and factoring. For RSA-type systems, n = p * q. Multiplying primes is simple; finding the factors of a properly generated large n is computationally difficult with known classical methods.
Modular inverses. The inverse of 3 modulo 11 is 4 because 3 * 4 mod 11 = 1. An inverse exists only when the value and modulus are relatively prime.
The discrete logarithm problem. Given g, p and g^a mod p, finding the private exponent a is hard in appropriately chosen large groups. ECC uses a related problem for elliptic-curve points.
Notation: c = m^e mod n means c is the remainder when m^e is divided by n.
Two further tools: The Chinese Remainder Theorem (CRT) reconstructs a value from its residues modulo coprime factors. Hensel lifting progressively extends a root modulo p to a root modulo p^2, p^3 and beyond. These two techniques are particularly important for RSA variants and the Takagi cryptosystem.
Chapter 4 / Quick reference
Which algorithm solves which problem?
Algorithm / family
Principal role
Mathematical foundation
Practical perspective
Diffie-Hellman
Key agreement
Finite-field discrete log / CDH
Foundational; must authenticate peers
RSA, RSA-OAEP, RSA-PSS
Encryption / signatures
RSA problem and integer factorization
Established with correct encoding and parameters
Multi-prime RSA
RSA optimization
Product of 3+ distinct primes
PKCS #1 describes support; smaller factors require care
Ed25519 widely deployed; secure nonces are critical
ECIES
Hybrid encryption framework
ECDH plus KDF and symmetric AEAD
Exact profile and encoding matter
Cramer-Shoup
Chosen-ciphertext-secure encryption
Decisional Diffie-Hellman (DDH)
Classic provable-security construction
Goldwasser-Micali
Probabilistic bit encryption
Quadratic residuosity
Theoretically influential, inefficient in practice
"Established" does not mean quantum-resistant. Classical factoring and discrete-logarithm systems are vulnerable to a sufficiently capable quantum computer. See the post-quantum discussion near the end.
Chapter 5 / Detailed algorithm guide
Explore the algorithms
Each entry begins with the idea in ordinary language, then explains a typical construction and the details that matter when implementing or evaluating the scheme. Mathematical details are expandable but the main explanations remain visible.
18 entries
01 / Key agreement
Diffie-Hellman (DH)
Whitfield Diffie and Martin Hellman, 1976; earlier classified work by Malcolm Williamson.
Foundation
Basic idea. Alice and Bob can arrive at the same mathematical secret even though they exchange their public values across an insecure network. An eavesdropper sees the public parameters and exchanged values, but cannot feasibly calculate the secret when the group is appropriately selected and the private exponents remain unknown.
Agree on a large prime modulus p and a generator g of a suitable subgroup.
Alice chooses a private exponent a and publishes A = g^a mod p. Bob chooses b and publishes B = g^b mod p.
Alice computes B^a mod p, while Bob computes A^b mod p. Both obtain g^(ab) mod p.
Feed the shared result and the relevant protocol context into a KDF. Use the resulting keys with authenticated symmetric encryption.
A = g^a mod p | B = g^b mod p Shared secret: K = B^a mod p = A^b mod p
Worked example. Choose p = 23, g = 5, Alice's a = 6 and Bob's b = 15. Alice sends A = 8, and Bob sends B = 19. Both calculate K = 2. These values are trivial to attack, but reveal the symmetry of the mathematics. Try the interactive DH lab.
Deeper technical view and security pitfalls
Diffie-Hellman is a key-agreement method, not an encryption algorithm or a digital signature scheme. Its security analysis distinguishes the discrete-logarithm problem, the computational Diffie-Hellman (CDH) problem and the decisional Diffie-Hellman (DDH) problem. Security depends on the precise group and protocol construction.
Unauthenticated DH is susceptible to a man-in-the-middle attack: an attacker negotiates a different secret with each party. Protocols address this with authenticated certificates, signatures, pre-shared keys or other authentication. Production systems also validate public inputs, select secure groups, use fresh randomness, apply appropriate KDFs and avoid small-subgroup attacks. Ephemeral DH can support forward secrecy.
Basic idea. RSA constructs a large composite modulus from secret prime factors. The public exponent lets anyone apply the public-key transformation, while a corresponding private exponent reverses it. The same underlying number-theory primitive can support encryption or signatures, but safe applications require distinct schemes and encodings.
Generate two unpredictable, sufficiently large, distinct primes p and q. Compute n = p*q and λ(n) = lcm(p-1, q-1).
Choose public exponent e relatively prime to λ(n) (commonly 65537). Compute private exponent d = e^(-1) mod λ(n).
Publish (n,e). Protect d, the primes and CRT parameters. For encryption, first use a secure randomized encoding such as RSA-OAEP.
Perform the RSA exponentiation on the encoded message. The receiver uses the private exponent (often accelerated using the CRT) and checks/decodes the result.
Textbook primitive: c = m^e mod n and m = c^d mod n
Worked example. Choose p=61, q=53, n=3233, e=17 and d=2753 (computed using φ(n)=3120; this also satisfies the needed inverse relation). Then m=65 transforms to c=2790, and private-key exponentiation recovers 65. Experiment with the RSA-family lab.
Two different safe uses.RSAES-OAEP specifies encryption with randomized encoding. RSASSA-PSS specifies probabilistic signatures over a hashed message. Simply "encrypting with the private key" is not an accurate description of a secure digital-signature protocol.
Deeper technical view: CRT, padding and attacks
The CRT can speed private operations: compute m_p = c^(d mod (p-1)) mod p and m_q = c^(d mod (q-1)) mod q, then reconstruct m modulo n. This approach avoids a single exponentiation over the full modulus.
Textbook RSA is deterministic and algebraically malleable; it does not provide semantic security. It is susceptible to chosen-ciphertext and related attacks when combined with unsafe encodings or error handling. Production libraries should provide padding-oracle-resistant decryption, input checks, blinding, side-channel resistance, secure key generation and CRT fault protection. The security of the RSA primitive is closely linked to the difficulty of the RSA inversion problem and to the practical hardness of factoring its modulus; these are distinct formal problems.
For contemporary deployments, RSA-2048 is commonly treated as roughly a 112-bit classical-security strength while RSA-3072 is roughly 128-bit strength. Applicable policy and lifetime requirements may call for larger keys. RSA is not post-quantum secure.
An RSA modulus built from at least three distinct prime factors.
Specialized optimization
Basic idea. Ordinary RSA commonly chooses n=p*q. Multi-prime RSA chooses n=p_1*p_2*...*p_t for t >= 3. Each prime factor is smaller than it would be in a conventional two-prime modulus of the same bit length. Consequently, private-key operations can be split into more, smaller modular exponentiations and recombined using the Chinese Remainder Theorem.
Choose t distinct large secret primes; calculate their product n.
Compute λ(n)=lcm(p_1-1, ..., p_t-1) and choose an exponent e invertible modulo λ(n).
Compute d=e^(-1) mod λ(n), and retain the separate CRT exponents d_i=d mod (p_i-1).
For private-key operations, calculate m_i=c^(d_i) mod p_i in each small modulus, and combine the residues with CRT.
n = p_1 * p_2 * p_3 (versus ordinary RSA: n = p * q)
Worked example. Using p_1=11, p_2=13, p_3=17 yields n=2431. With e=17, the teaching example uses φ(n)=1920 and d=113. Each private calculation can be done separately modulo 11, 13 and 17 before recombination. Select "Multi-prime RSA" in the lab.
Deeper technical view: why more primes can be faster, and why that matters
Computing with three approximately one-third-sized primes can make CRT exponentiations cheaper than operating over two approximately one-half-sized primes. The benefit depends on processor architecture, implementation, parallelism and factor sizes. PKCS #1 version 2.2 explicitly defines multi-prime key representations, including otherPrimeInfos for additional prime factors and CRT coefficients.
Security trade-off: keeping the same modulus length while increasing the number of primes reduces the bit length of the smallest factor, potentially making factor-discovery techniques (including the elliptic-curve factoring method) more attractive. A secure implementation must choose the number and size of primes with security guidance in mind. Multi-prime RSA is not simply "more secure" because it uses more prime numbers. Interoperability support is also less ubiquitous than conventional two-prime RSA.
An RSA-type construction using a repeated prime factor, usually n = p^k*q.
Research-oriented
Basic idea. Unlike multi-prime RSA, which multiplies distinct primes, a multi-power construction uses at least one prime power. The commonly discussed shape is n=p^k*q, with k >= 2 and distinct secret primes p and q. The public transformation still resembles RSA exponentiation, but the private reconstruction must account for a residue modulo p^k.
Select secret primes p and q and a small integer k >= 2. Compute n = p^k * q.
For the unit group, calculate φ(n) = p^(k-1)*(p-1)*(q-1) or λ(n) = lcm(p^(k-1)*(p-1), q-1) for odd primes.
Choose e coprime to the relevant group exponent and find an inverse d. Use a valid randomized encryption encoding that produces an acceptable group element.
Recover the plaintext residues modulo p^k and q and combine them with CRT. Special algorithms can accelerate the first residue calculation.
n = p^k * q | φ(n) = p^(k-1)*(p-1)*(q-1)
Worked example. Let p=11, q=17 and k=2. Then n=11^2*17=2057 and φ(n)=1760. For e=17, d=1553 is an inverse modulo 1760. With m=42, the ciphertext is c=1742, and private exponentiation recovers 42. Test the p-squared RSA mode.
Deeper technical view: limits of the textbook formula
For an RSA-type map on Z_n^* (integers relatively prime to n), using an inverse exponent ensures correct reversal. A critical subtlety is that n=p^k*q contains repeated factors: plain exponentiation does not necessarily recover plaintexts divisible by p. Accordingly, the domain or encoding must be designed with that restriction in mind. This differs from the ordinary square-free RSA modulus.
"Multi-power RSA" describes a family of prime-power RSA-type ideas, not an invitation to take a standard PKCS #1 implementation and simply replace p*q with p^2*q. Correctness proofs, secure parameters, factoring resistance, padding and fault countermeasures must be revisited.
Tsuyoshi Takagi's fast RSA-type construction, proposed in 1998.
Hensel-lifting method
Basic idea. The Takagi cryptosystem is a specific way of implementing the prime-power RSA idea. Its important innovation is a fast private-key operation when n=p^k*q. Rather than performing an unnecessarily large exponentiation modulo p^k, the decryptor first finds a root modulo the small prime p, then lifts that root to modulo p^2, and so forth.
Generate n=p^k*q and select an appropriate public exponent e, with the scheme's domain and invertibility conditions satisfied.
Encrypt a permissible message with the RSA-like map c=m^e mod n (a real secure scheme also requires appropriate encoding).
Find m_p, the e-th root of c modulo p; compute the residue modulo q separately.
Use the CRT to combine the residues modulo p^k and q into the unique message modulo n.
f(x) = x^e - c = 0 (mod p^k) x_next = x + t*p^j (when lifting mod p^j to mod p^(j+1))
Worked example. For n=11^2*17=2057, e=17, and m=42, ciphertext is 1742. The root modulo 11 is 9. Lifting gives 9+3*11=42 modulo 121. The root modulo 17 is 8. CRT combines 42 mod 121 with 8 mod 17, producing 42. The Takagi laboratory shows the actual lift.
Deeper technical view: the lifting equation
If a current root x satisfies x^e = c (mod p^j), seek x' = x+t*p^j, with t chosen modulo p. The linearized relation is (c-x^e)/p^j = t*e*x^(e-1) (mod p). If e*x^(e-1) has an inverse modulo p, solve for t and repeat. The conditions require care, notably when p divides x or e.
Takagi's published work compares decryption performance against conventional CRT-RSA and multi-prime RSA under particular key sizes and implementation assumptions. Those reported gains are historical benchmark observations, not a guarantee that a prime-power RSA implementation is automatically superior or secure under modern deployment constraints.
Basic idea. Rabin encryption is remarkably simple: square the plaintext modulo a composite number. Its special theoretical feature is that extracting modular square roots for random inputs is closely connected to factoring the modulus. Its main practical complication is that decrypting a typical ciphertext yields four possible plaintext values, not automatically one.
Choose two secret, distinct Blum primesp and q, each satisfying p mod 4 = 3 and q mod 4 = 3. Publish n = p*q.
Represent the plaintext as a suitable integer m, typically relatively prime to n, and compute c=m^2 mod n.
Use secret p and q to find the two roots of c modulo each prime. For Blum primes, a square root can be found with c^((p+1)/4) mod p and similarly for q.
Combine the two independent sign choices using CRT. This usually produces four roots modulo n; the message encoding or protocol must disambiguate them.
Encryption: c = m^2 mod n Decryption: find all x such that x^2 = c (mod n)
Worked example. Let p=7, q=11, n=77, and m=13. Encryption gives c=15. The four square roots of 15 modulo 77 are 13, 20, 57 and 64. All four square to 15 modulo 77, so pure squaring does not identify the intended message. Run the Rabin root calculator.
Deeper technical view: security proof and practical difficulties
For a suitable composite modulus, a method that can obtain arbitrary modular square roots can be used to factor n with nonnegligible probability. This makes Rabin's one-way property particularly interesting theoretically. However, textbook Rabin encryption is deterministic, ambiguous and not secure against chosen-ciphertext attacks. Naive redundancy is not a complete modern security proof.
The commonly repeated description that Rabin uses "e=2 and d=1/2" is misleading: modular square-root extraction is not equivalent to raising the ciphertext to one universal decryption exponent. Concrete secure Rabin-derived schemes require carefully specified encodings and transformations; the tutorial's square-root primitive is only an illustration.
Basic idea. ElGamal turns the Diffie-Hellman idea into public-key encryption. The sender creates a temporary (ephemeral) exponent that generates a shared masking value using the recipient's public key. The message is multiplied by that mask. The recipient's secret exponent reconstructs the mask and removes it.
Choose a suitable cyclic group, such as a subgroup of the nonzero integers modulo a large prime p, with generator g. The recipient chooses private key x and public key y=g^x mod p.
The sender chooses a fresh random exponentk for each encryption.
Compute c_1=g^k mod p and c_2=m*y^k mod p. Transmit the ciphertext pair (c_1,c_2).
The recipient calculates s=c_1^x mod p and recovers m=c_2*s^(-1) mod p.
Public key: y = g^x mod p Encrypt: (c1,c2) = (g^k, m*y^k) mod p Decrypt: m = c2 * (c1^x)^(-1) mod p
ElGamal is probabilistic: the same message encrypted twice with new values of k normally produces different ciphertexts. This addresses an important weakness of deterministic textbook RSA, but ElGamal's textbook form remains malleable. Try the ElGamal calculator.
Deeper technical view: assumptions, encodings and malleability
The basic form commonly relies on the decisional Diffie-Hellman assumption for semantic security in a suitable group. It operates on group elements; arbitrary files and messages must first be encoded or, more appropriately, handled using a hybrid encryption scheme with a KDF and authenticated symmetric encryption.
Multiplying an ElGamal ciphertext component by a known factor predictably changes the decrypted plaintext, so textbook ElGamal does not achieve chosen-ciphertext security. Correct implementations must validate group membership, choose fresh unpredictable exponents, use secure groups and avoid malformed-point or subgroup attacks in elliptic-curve variants. Some older PGP/OpenPGP constructions have used ElGamal encryption, but this should not be confused with a recommendation for a new system.
Basic idea. Paillier is a randomized encryption scheme with a special property: multiplying two ciphertexts produces an encryption of the sum of their underlying plaintexts. This is called additive homomorphism. It allows, for example, a trusted party holding the private key to decrypt an aggregate of encrypted votes or measurements without decrypting each input separately.
Generate secret primes p and q such that the required key-generation conditions hold. Compute n=p*q, λ=lcm(p-1,q-1) and work modulo n^2.
In a common simplified variant, set g=n+1 and compute μ=λ^(-1) mod n where the inverse exists. Publish (n,g) and keep (λ,μ) private.
Encode m as an integer from 0 to n-1, choose a fresh random r coprime to n and compute c=g^m*r^n mod n^2.
Decrypt using m=L(c^λ mod n^2)*μ mod n, where L(u)=(u-1)/n for values congruent to 1 modulo n.
E(m;r) = g^m * r^n mod n^2 E(m1;r1) * E(m2;r2) mod n^2 = E(m1+m2 mod n; r1*r2 mod n)
Worked example. With p=7, q=11, n=77, λ=30, g=78 and μ=18, encrypting 9 with r=2 yields 4407; encrypting 4 with r=3 yields 2539. Multiplying the ciphertexts modulo 77^2 decrypts to 13, the sum of the messages. Run the Paillier homomorphism lab.
Deeper technical view: security model and limitations
Paillier's semantic security is associated with the decisional composite residuosity assumption (DCRA). Its randomizer must be selected from the multiplicative group of units modulo n. The system supports ciphertext addition and multiplication of an encrypted value by a known plaintext constant, but it does not natively permit arbitrary ciphertext-by-ciphertext multiplication of plaintext values.
Additive homomorphism also creates opportunities for deliberate ciphertext manipulation. A real application must provide authentication, input validation, range proofs and/or other controls according to its threat model. The plaintext arithmetic is modulo n, so aggregators must choose bounds and encodings that do not introduce unnoticed wraparound.
Josh Benaloh's dense probabilistic encryption, developed in the 1980s and 1990s.
Historically significant
Basic idea. Benaloh generalizes earlier probabilistic bit-encryption ideas so that one ciphertext can encode an integer from 0 through r-1, for a chosen message modulus r. Like Paillier, it supports encrypted addition. Its performance and correctness depend sensitively on the selection of r, the secret primes and a public element y.
Choose an odd integer message modulus r and secret primes p,q such that r divides p-1, gcd(r,(p-1)/r)=1 and gcd(r,q-1)=1.
Compute n=p*q and choose a unit y mod n. Check the corrected generator condition: for every prime factor s of r, y^((p-1)/s) != 1 mod p.
Publish (n,r,y). Encrypt m in {0,...,r-1} with a new random unit u: c=y^m*u^r mod n.
To decrypt, raise c to (p-1)/r modulo p, eliminating the randomizer. Recover m by finding the exponent of the corresponding base in a subgroup of order r.
E(m;u) = y^m * u^r mod n E(m1;u1)*E(m2;u2) = E(m1+m2 mod r; u1*u2 mod n)
Worked example. Take r=5, p=11, q=7, n=77 and y=2. With m=2 and u=3, c=2^2*3^5 mod 77=48. Decryption uses 48^2 mod 11=5 and the fact that (2^2)^2 mod 11=5, recovering m=2. Try the Benaloh lab.
Deeper technical view: an important correction to older descriptions
Older descriptions sometimes require only that y^(φ(n)/r) != 1 mod n. Researchers later showed that this test by itself does not guarantee that all r intended plaintext classes are distinguishable, particularly when r is composite. The stronger test for every prime divisor s of r prevents that collapse under the stipulated parameter conditions.
Decryption may involve a discrete logarithm in the small subgroup, so choosing r entails a balance between message capacity and decryption effort. Benaloh is valuable pedagogically in the history of homomorphic encryption and electronic voting, but modern deployments should carefully study the corrected scheme and its application-level proofs.
Simple Password Exponential Key Exchange; David P. Jablon, 1996.
PAKE protocol
Basic idea. Ordinary Diffie-Hellman does not tell Alice whether the other party is really Bob. SPEKE belongs to the family of password-authenticated key exchange (PAKE) protocols: parties who share a low-entropy password derive a cryptographic group generator from that password, and then perform a Diffie-Hellman-like exchange. Correctly designed PAKEs aim to prevent an eavesdropper from testing large numbers of password guesses against a captured exchange without interacting with a party.
Alice and Bob begin with the same password and agreed group parameters. A protocol-specified transformation maps the password to a valid generator g_pw of the intended subgroup.
Alice chooses a fresh private exponent a and sends A=g_pw^a mod p. Bob chooses b and sends B=g_pw^b mod p.
Both derive the same Diffie-Hellman group element g_pw^(ab) mod p when their passwords and group operations agree.
A secure protocol applies a specified KDF and performs authenticated key confirmation tied to identities, session roles and the communication transcript.
g_pw = MapPasswordToGroup(password) A = g_pw^a mod p | B = g_pw^b mod p
Intuition. If Alice and Bob type the same password, they begin from a consistent group base and can derive a matching secret. However, that observation alone is not a security proof. The password-to-group mapping, subgroup checks, protocol transcript and key-confirmation logic are essential parts of real SPEKE.
Deeper technical view: offline guessing, protocol attacks and patches
SPEKE's security goals differ from simply hashing a password and using it as an AES key. A properly designed PAKE limits the usefulness of captured traffic for offline dictionary search; it cannot prevent online password guessing, which applications must separately control. SPEKE's original and older standardized variants have undergone security analysis, including attacks involving parallel sessions and key malleability.
Work by Hao and colleagues identified issues in older SPEKE specifications and proposed a patched construction known as P-SPEKE; a revision of ISO/IEC 11770-4 incorporated a patch. New systems should use a rigorously reviewed PAKE profile rather than implementing the short equations on this page in isolation. Other PAKE protocols include SPAKE2 (RFC 9382) and SPAKE2+ (RFC 9383); these are distinct algorithms, not alternative names for SPEKE.
Menezes-Qu-Vanstone (MQV), 1995; later hashed MQV (HMQV) variants.
Authenticated key agreement
Basic idea. MQV improves on unauthenticated Diffie-Hellman by combining each participant's long-term (static) key pair with a new ephemeral key pair. The goal is that both endpoints derive a session key while binding the exchange to the intended parties' identities and long-term keys. It exists in finite-field and elliptic-curve forms.
Alice and Bob each maintain a static private/public key pair associated with an authenticated identity.
For each session, each party creates a fresh ephemeral key pair and exchanges the ephemeral public key.
The protocol mixes static private-key material and ephemeral private-key material using specified functions of the exchanged public shares.
The parties compute a common group element and derive session keys with appropriate KDF/context binding and, where required, explicit key confirmation.
Why this differs from ordinary ECDH. If two strangers perform bare ECDH, they can establish a common secret but have no assurance who is at the other end of the channel. MQV integrates long-term authenticated keys into the mathematical agreement itself. HMQV uses hashing in the coefficient derivation and has its own security analysis and implementation requirements.
In the elliptic-curve family, imagine Alice's static pair (a,A=aG), ephemeral pair (r_A,R_A=r_A G), and Bob's corresponding (b,B), (r_B,R_B). In a simplified schematic, each side combines a private term like s_A=r_A+f(R_A)*a mod q with a peer public point like R_B+f(R_B)*B, producing matching scalar-multiple point results under the specified rules. This is a teaching sketch, not a normative, fully specified MQV implementation.
The authenticating properties require validated public keys, correct subgroup handling, an approved key derivation scheme and well-defined identifiers. Implementations must also distinguish implicit authentication from explicit key confirmation. NIST SP 800-56A describes MQV-based key-establishment variants and their validation requirements.
A family of public-key techniques, not one particular cipher.
Modern foundational family
Basic idea. ECC replaces integer exponentiation modulo a prime with a different hard mathematical problem: recovering a scalar from an elliptic-curve point multiplication. A curve defines a set of points with a special addition rule. Repeatedly adding a base point to itself is efficient; reversing that calculation for properly selected large groups is difficult.
For a short Weierstrass curve: y^2 = x^3 + a*x + b (mod p) Public key Q = d*G where d is a private scalar
Select a standardized curve and a base point G of large prime order q.
Select private scalar d from the allowed range and compute public point Q=d*G.
To add two distinct points P=(x1,y1) and Q=(x2,y2), calculate a slope using modular division and then derive a new point R=P+Q.
Use point multiplication in a complete protocol, such as ECDH for keys or ECDSA for signatures.
A small educational curve. Consider y^2=x^3+2x+2 mod 17 with base point G=(5,1), which has order 19. Doubling produces 2G=(6,3); five copies produce 5G=(9,16). Actual ECC standards use vastly larger fields and carefully evaluated groups. Explore the point-multiplication lab.
Deeper technical view: point operations, parameter validation and curve models
For distinct points with x1 != x2, compute s=(y2-y1)*(x2-x1)^(-1) mod p, x3=s^2-x1-x2 mod p, and y3=s*(x1-x3)-y1 mod p. To double a point on the illustrated curve, replace the slope with s=(3*x1^2+a)*(2*y1)^(-1) mod p. The identity element is the point at infinity. These formulas require exceptional-case handling; they are not automatically safe for arbitrary curves.
ECC includes multiple curve models, notably short Weierstrass curves (for example P-256), Montgomery curves (used by X25519) and Edwards curves (used by Ed25519). The finite-field prime, curve coefficients, subgroup order, cofactor, encoding and point validation are security-critical. Roughly 256-bit elliptic-curve public keys can provide approximately 128-bit classical security, subject to algorithm and curve choice. ECC, like RSA, is vulnerable to a sufficiently capable quantum computer.
Elliptic-Curve Diffie-Hellman and modern Montgomery-curve interfaces.
Widely deployed
Basic idea. ECDH is the elliptic-curve counterpart of ordinary Diffie-Hellman. Instead of exchanging powers of a generator, the two parties exchange scalar multiples of a common point. An eavesdropper can see both public points but should not be able to determine the shared result.
Alice chooses private scalar a and computes A=aG. Bob chooses b and computes B=bG.
They exchange public points A and B, according to the curve's encoding and validation requirements.
Alice computes aB; Bob computes bA. Both obtain (ab)G.
A KDF converts the resulting shared material into keys, binding identities, algorithm choices and transcript information where required.
a*(b*G) = b*(a*G) = (a*b)*G
X25519 is a standardized function for performing Diffie-Hellman with Curve25519, specified by RFC 7748. X448 supplies a higher-strength counterpart on Curve448. X25519 produces a shared secret from a local scalar and the peer's public input; the application still needs authentication and key derivation. RFC 7748 also discusses rejecting or aborting on an all-zero shared result.
Deeper technical view: ephemeral keys and protocol security
Ephemeral ECDH (often written ECDHE) uses fresh private scalars per session and can support forward secrecy when implemented in a suitable authenticated protocol. The expression (ab)G alone does not prove the peer's identity. TLS-style protocols bind key agreement to authenticated transcript data and derive multiple traffic keys with a KDF.
X25519's Montgomery-ladder operation and coordinate representation differ from the ordinary point-addition formulas shown in the ECC introduction. Do not use the toy ECC calculator as a drop-in X25519 implementation.
Basic idea. ECDSA lets an owner of an elliptic-curve private key sign a message. A recipient verifies the signature using only the public key, a hash of the message and the group operations. The signature provides evidence of origin and integrity; it does not encrypt or conceal the underlying message.
Generate a private scalar d and public point Q=dG, where the generator has order q.
Hash the message to an appropriately processed integer z and obtain a unique, secret per-signature scalar k.
Calculate R=kG, let r=x(R) mod q, and compute s=k^(-1)*(z+r*d) mod q. Retry under the scheme's rules if a required value is zero.
The verifier processes (r,s) with the public key and checks that a derived point's x-coordinate matches r under the standard's rules.
Signature: (r,s), where r = x(kG) mod q and s = k^(-1) * (z + r*d) mod q
Security-critical rule. Reusing k on two different messages or leaking part of it can reveal the private key. Deterministic nonce-generation techniques (such as RFC 6979 for certain ECDSA profiles) reduce dependence on fresh randomness at signing time but still require a secure implementation.
Deeper technical view: how verification works
The verifier computes w=s^(-1) mod q, u1=z*w mod q and u2=r*w mod q, then evaluates V=u1*G+u2*Q. If the inputs are valid, verifying x(V) mod q=r establishes the ECDSA signature condition. Real verification also checks signature ranges, point validity and correct message-hash processing.
NIST FIPS 186-5 specifies ECDSA and approved signature methods; NIST SP 800-186 supplies recommended curve parameters. Signature encodings, side channels, public-key provenance and hash choices remain critical.
Basic idea. EdDSA is a family of signature schemes built on Edwards-type elliptic curves. Ed25519 is a widely used instantiation; Ed448 is another. Their formulas are designed for efficient, robust implementations and conventionally derive a per-message nonce deterministically from private-key-derived secret material and the message.
Create a secret seed and derive an appropriately clamped secret scalar and additional nonce-derivation material. Compute the public point from the base point.
Hash the secret prefix and message to obtain a deterministic nonce scalar; compute the corresponding curve point R.
Hash R, the public key and the message to obtain a challenge scalar.
Combine the nonce and private scalar into a signature value S. Verify a corresponding elliptic-curve group equation using the public key.
S = r + H(R || A || M) * a (mod L) Check a corresponding group relation involving S*B, R and A.
Ed25519 versus X25519. The names resemble each other because the associated curves are mathematically related, but Ed25519 is a digital-signature algorithm and X25519 is a key-agreement function. They are not interchangeable. Do not assume keys can be reused across those roles without a carefully specified design.
Deeper technical view: what "deterministic" means
In pure Ed25519, the nonce is derived from a private-key prefix and the message rather than drawn afresh by an external random-number generator for every signature. This avoids the classic ECDSA failure mode of accidentally repeating a random k, but it does not eliminate the need for secure seed generation, safe storage or resistance to faults and side channels. Ed25519 and Ed448 use different parameter sets and encodings.
FIPS 186-5 includes EdDSA as a standardized signature technique, subject to the standard's requirements. EdDSA does not provide confidentiality or a shared secret.
Elliptic Curve Integrated Encryption Scheme, a family of hybrid constructions.
Hybrid encryption
Basic idea. ECC itself does not define a universal message-encryption algorithm. ECIES addresses that gap by using an elliptic-curve shared secret to derive symmetric keys, then using symmetric cryptography to encrypt the message. Different ECIES profiles specify different curve choices, KDFs, message formats and authentication methods.
The recipient publishes an authenticated ECC public key Q=dG.
The sender selects an ephemeral private scalar k and sends the corresponding public point R=kG.
The sender computes Z=kQ, while the recipient can later compute the same value as dR.
Apply an approved KDF with required context and derive keys for an authenticated symmetric encryption algorithm; transmit the ephemeral public key, ciphertext and authentication tag.
The recipient derives matching keys, verifies the authentication tag and only then accepts the plaintext.
Sender: Z = k * Q | Receiver: Z = d * R Symmetric key = KDF(Z, context)
ECIES illustrates a major practical pattern in cryptography: asymmetric mathematics establishes a secret, while a fast authenticated cipher protects the message itself. A receiver must know the exact algorithm profile and correctly parse, validate and authenticate all relevant fields.
Deeper technical view: standards and misuse hazards
"ECIES" is a family name; implementations vary. Some historical profiles derive an encryption key and a separate MAC key, while modern constructions may use authenticated encryption with associated data (AEAD). Security depends on the curve, KDF, randomness, key confirmation choices, point validation and the integrity of the recipient's public key.
Static versus ephemeral key decisions determine security properties such as forward secrecy; do not assume ECIES provides sender authentication merely because the recipient can decrypt. Public-key authentication and message authentication are different requirements.
Basic idea. Cramer-Shoup was designed to address an important weakness of basic ElGamal: an active attacker may modify ciphertexts and ask a decryption service how they behave. The Cramer-Shoup scheme augments an ElGamal-like construction with extra public-key components and a cryptographic hash-based consistency check.
Generate a suitable group and several related public-key elements derived from a collection of secret exponents.
Choose a fresh random exponent and compute public ciphertext components such as u1=g1^r and u2=g2^r.
Mask the message using another group element and compute a hash challenge from ciphertext components.
Construct an authentication-related group component using the challenge; append it to the ciphertext.
Before returning a plaintext, the decryptor verifies the ciphertext consistency equation. Invalid ciphertexts are rejected.
The resulting construction provided a foundational example of public-key encryption proved secure against adaptive chosen-ciphertext attacks (IND-CCA2) under conventional assumptions for an appropriate group and hash construction. It helped bridge a gap between abstract security definitions and practical algebraic cryptosystems.
Deeper technical view: why the check changes security
In a typical presentation, encryption outputs four values (u1,u2,e,v), where a challenge α=H(u1,u2,e) is used to form v=c^r*d^(r*α) for suitable public group elements c and d. Decryption reconstructs the expected relation and rejects altered ciphertexts before unmasking the message.
The hash-based binding is not a cosmetic checksum: it is structurally tied to the security proof. Using unaudited parameter sets or modifying the verification rules voids the intended assurance.
Basic idea. Goldwasser-Micali is a historically pivotal probabilistic public-key encryption construction. It encrypts a single bit by hiding a mathematical property: whether a chosen number is a quadratic residue modulo a composite number. Its importance lies in showing how encryption can be formally defined to conceal information about a message.
Generate large secret primes p and q, compute n=p*q, and select a public element x that is a quadratic nonresidue modulo both primes while having Jacobi symbol +1 modulo n.
To encrypt a bit b, choose a random unit r modulo n and compute c=r^2*x^b mod n.
The recipient uses the secret factors to determine whether the result is a quadratic residue modulo a secret prime, thereby recovering b.
Encrypt a longer message by encrypting each bit separately, which is why the original construction has substantial ciphertext expansion.
E(b;r) = r^2 * x^b mod n where b is 0 or 1
Multiplying Goldwasser-Micali ciphertexts produces an encryption of the XOR (addition modulo 2) of their bits. It is therefore a simple example of a homomorphic property, though its ciphertext expansion makes it inefficient for general-purpose encryption.
Deeper technical view: why this matters historically
Goldwasser and Micali introduced a rigorous way to think about probabilistic encryption and semantic security, influencing later cryptography far beyond this specific bit-encryption system. In the intended setting, distinguishing whether a Jacobi-1 element is a square modulo the unknown-factor composite is believed to be computationally hard.
The scheme demonstrates why randomized encryption can hide even highly predictable plaintexts. It does not give chosen-ciphertext security as a raw textbook construction, and its asymptotic properties alone do not make it a practical modern messaging scheme.
These exercises run completely inside this HTML file using BigInt. Select a lab, enter small values and press Calculate. Every exercise reports intermediate values and a correctness check.
Educational arithmetic only.The examples omit secure randomness, real-world key sizes, secure padding, full protocol validation, side-channel defenses and production cryptographic libraries. Results are useful for learning, not for protecting actual information.
Lab 1. Diffie-Hellman agreement
Use the fixed teaching group p=23, g=5. Change Alice's and Bob's secret exponents, then compare their independently calculated keys.
Press Calculate to see the exchange.
Lab 2. RSA, multi-prime, multi-power and Takagi
Choose the construction. The calculator shows the factorization, public and private exponents, ciphertext, recovered message and (where relevant) the CRT or Hensel-lifting steps. All modes require a message relatively prime to the modulus.
Choose a construction and calculate.
Lab 3. Rabin and the four-root problem
With p=7, q=11 and n=77, encrypt a nonzero message coprime to 77. Observe every candidate plaintext returned by modular square-root extraction.
Try the default value 13.
Lab 4. ElGamal randomized encryption
Fixed teaching group: p=23, g=5, recipient private key x=6. Choose a nonzero message and a fresh-looking illustrative ephemeral exponent k.
Change k and see why ElGamal is randomized.
Lab 5. Paillier encrypted addition
Fixed toy parameters p=7, q=11, n=77, g=78. Encrypt two messages with independent randomizer inputs; multiply ciphertexts and decrypt the total.
The decrypted aggregate should equal (m1 + m2) mod 77.
Lab 6. Benaloh encrypted addition
Fixed valid toy key: r=5, p=11, q=7, n=77, y=2. Enter two plaintexts modulo 5. This lab directly performs the finite-subgroup discrete-log lookup needed for decryption.
See how a product of ciphertexts encodes a sum.
Lab 7. Elliptic-curve point multiplication
This lab works on y^2=x^3+2x+2 mod 17 with G=(5,1) of order 19. It computes the public points and the ECDH-like shared point with exact modular point addition.
The conceptual demonstration uses a tiny safe-prime group p=23 and subgroup order 11. It uses a deliberately simple, noncryptographic character mapping only to illustrate why a generator can depend on a password. This is not SPEKE or a secure PAKE implementation.
Try changing one password; no real authentication is performed.
Even coincidentally matching toy outputs are not evidence of secure authentication. Real SPEKE uses a carefully specified password-to-group map, validation, transcript binding and key confirmation.
Chapter 7 / Applying the concepts
How would you choose among these techniques?
Secure a connection
Use a vetted authenticated key-establishment protocol (often including ephemeral ECDH or X25519), a standard KDF and authenticated encryption. DH by itself does not authenticate the peer.
Sign software or records
Choose an approved and appropriately implemented signature method, such as EdDSA, ECDSA or RSA-PSS. Include trustworthy public-key distribution and certificate/key lifecycle processes.
Compute on encrypted totals
Paillier and Benaloh illustrate addition on ciphertexts. A real privacy system may also need zero-knowledge proofs, access controls and measures against inference from aggregate results.
Classical versus post-quantum cryptography
RSA, Diffie-Hellman and ECC rely on factoring or discrete-logarithm-related problems that are vulnerable to sufficiently powerful fault-tolerant quantum computers. NIST's post-quantum standard FIPS 203 specifies ML-KEM for key establishment, while FIPS 204 specifies ML-DSA digital signatures. Those algorithms use different mathematics; they are not ECC or RSA variants. For further reading, see the separate lattice cryptography tutorial.
Important design principle. Do not select an algorithm on the basis of key length or its mathematical novelty alone. Security depends on standards compliance, specific parameter sets, protocol binding, padding, randomness, error handling, implementation quality and the threat model.
Chapter 8 / Knowledge check
Test your understanding
Choose one answer for each question and then check your results. You can revise the answers and check again.
Chapter 9 / Terminology
Essential glossary
Term
Meaning
Asymmetric key pair
A mathematically related public key and private key, used according to the chosen cryptographic function.
CRT (Chinese Remainder Theorem)
Method of reconstructing an integer from residues modulo pairwise coprime factors. Used to accelerate RSA decryption and signatures.
Elliptic-curve point
A pair of field elements meeting a specified elliptic-curve equation, or the point at infinity.
Forward secrecy
Protection of earlier session keys against later compromise of certain long-term secrets, when the protocol provides it.
Hensel lifting
Extending a solution of a polynomial congruence modulo p to solutions modulo higher powers of p under suitable conditions.
IND-CPA / IND-CCA
Indistinguishability under chosen-plaintext / chosen-ciphertext attack, respectively. Security definitions for encryption schemes.
KDF
Key derivation function; turns shared secret material, salts and context into cryptographic keys.
Homomorphic encryption
Encryption that allows certain computations directly on ciphertexts, yielding encrypted results corresponding to operations on plaintexts.
Nonce / ephemeral scalar
A value intended for one cryptographic operation or session; reuse can break security in some protocols, particularly ECDSA.
PAKE
Password-authenticated key exchange; key agreement incorporating a shared password with protection against practical passive offline guessing under its security model.
Prime-power modulus
A modulus such as p^2*q that contains a repeated prime factor; important in multi-power RSA.
Quadratic residue
A value that is the square of another value modulo a specified modulus.
Side-channel attack
Attack that exploits timing, power consumption, cache behavior, faults or other observable implementation effects rather than directly solving the cryptographic problem.
Symmetric encryption
Encryption and decryption using a shared secret key; typically handles bulk message data after public-key establishment.
Chapter 10 / Further study
Primary standards and research references
These links lead to foundational standards, peer-reviewed research or original publications. Citations next to the individual algorithm entries point to relevant items below.
Moriarty, K. et al. PKCS #1: RSA Cryptography Specifications Version 2.2. RFC 8017 (2016). IETF RFC text. Includes multi-prime RSA and RSA-OAEP/PSS.
NIST. SP 800-56A Rev. 3: Recommendation for Pair-Wise Key-Establishment Schemes Using Discrete Logarithm Cryptography. (2018). Official NIST page.
NIST. SP 800-56B Rev. 2: Recommendation for Pair-Wise Key-Establishment Using Integer Factorization Cryptography. (2019). Official NIST page.
NIST. FIPS 186-5: Digital Signature Standard. (2023). Official NIST page.
NIST. SP 800-186: Recommendations for Discrete Logarithm-based Cryptography: Elliptic Curve Domain Parameters. (2023). Official NIST page.
Takagi, T. Fast RSA-Type Cryptosystem Modulo p^k q. Advances in Cryptology - CRYPTO '98, LNCS 1462, pp. 318-326 (1998). Research record and DOI.
Takagi, T. A Fast RSA-Type Public-Key Primitive Modulo p^k q Using Hensel Lifting. IEICE Transactions on Fundamentals, E87-A(1), pp. 94-101 (2004). Publisher abstract.
Menezes, A., van Oorschot, P. and Vanstone, S. Handbook of Applied Cryptography. CRC Press (1996), especially chapters 8 and 12. Author-hosted book chapters.
Paillier, P. Public-Key Cryptosystems Based on Composite Degree Residuosity Classes. EUROCRYPT '99 (1999). Original paper copy.
Fousse, L., Lafourcade, P. and Alnuaimi, M. Benaloh's Dense Probabilistic Encryption Revisited. (2011). Author-hosted research paper. Explains corrected public-key generation conditions.
Jablon, D. P. Strong Password-Only Authenticated Key Exchange. ACM Computer Communication Review (1996). Original paper.
Hao, F., Metere, R., Shahandashti, S. F. and Dong, C. Analysing and Patching SPEKE in ISO/IEC. (2018). Research preprint.
Ladd, W. SPAKE2, a Password-Authenticated Key Exchange. RFC 9382 (2023). RFC text.
Taubert, T. and Wood, C. A. SPAKE2+, an Augmented Password-Authenticated Key Exchange Protocol. RFC 9383 (2023). RFC text.
Langley, A., Hamburg, M. and Turner, S. Elliptic Curves for Security. RFC 7748 (2016). RFC text.
Josefsson, S. and Liusvaara, I. Edwards-Curve Digital Signature Algorithm (EdDSA). RFC 8032 (2017). RFC text.
Cramer, R. and Shoup, V. A Practical Public Key Cryptosystem Provably Secure against Adaptive Chosen Ciphertext Attack. CRYPTO '98 (1998). Research record.
Goldwasser, S. and Micali, S. Probabilistic Encryption and How to Play Mental Poker Keeping Secret All Partial Information. STOC '82 (1982). ACM paper. See also JCSS (1984).
NIST. FIPS 203: Module-Lattice-Based Key-Encapsulation Mechanism Standard (ML-KEM). (2024). Official standard.
NIST. FIPS 204: Module-Lattice-Based Digital Signature Standard (ML-DSA). (2024). Official standard.
Prepared as an expanded teaching edition, October 2026. Real-world cryptographic choices should be checked against current standards, approved implementations and applicable organizational policy.