Belajar
← All lessons

How public-key cryptography works

Encrypt with the public key, decrypt with the private one

Ana
Eve (Wi-Fi)
Bob

bob.js

// Bob, onceconst p = 61, q = 53;const n = p * q;               // 3233const phi = (p - 1) * (q - 1); // 3120const e = 17;const d = modInverse(e, phi);  // 2753publish({ n, e });  // public key: share itkeep({ d });        // private key: keep it

message.js

// Ana, with only the public keyconst bytes = new TextEncoder().encode(message);const cipher = [...bytes].map(  (m) => modPow(m, e, n));  // m^e mod nsend(cipher); // Bob, with the private keyconst plain = cipher.map(  (c) => modPow(c, d, n));  // c^d mod nnew TextDecoder().decode(new Uint8Array(plain));

Make your own key pair then encrypt one letter

First prime p
Second prime q
Your toy keys
A letter to encryptBob decrypts withPrivate key dPublic key e
The math
Eve tries to factor n

A real n has 617 digits. No known method can factor it in any useful time

rsa.js

const n = p * q;const phi = (p - 1) * (q - 1);const e = 17; // 17 if it shares no factor with phiconst d = modInverse(e, phi); const c = modPow(m, e, n);    // anyone can do thisconst back = modPow(c, d, n); // only Bob can do thisconst nope = modPow(c, e, n); // doesn't give m back

eve.js

// Eve, trying to rebuild p and q from nfor (let f = 2; f * f <= n; f++) {  if (n % f === 0) return [f, n / f];}

Real-size RSA with random padding

Message
A 2048-bit key pair made in your browser
Ciphertexts, newest first

    RSA-OAEP fits at most 190 bytes with this key, so real systems use it to encrypt a random AES key, not the message

    webcrypto.js

    const keys = await crypto.subtle.generateKey({  name: "RSA-OAEP", modulusLength: 2048,  publicExponent: new Uint8Array([1, 0, 1]), // 65537  hash: "SHA-256",}, false, ["encrypt", "decrypt"]); // random padding: never the same twiceconst cipher = await crypto.subtle.encrypt(  { name: "RSA-OAEP" }, keys.publicKey, bytes); const plain = await crypto.subtle.decrypt(  { name: "RSA-OAEP" }, keys.privateKey, cipher);

    Topics

    Next: How digital signatures work

    Open lesson