Every time you load a page over HTTPS, two very different kinds of encryption work together. An asymmetric algorithm lets your browser and a server it has never met agree on a secret over a public network. Then a symmetric cipher, AES or ChaCha20, encrypts everything that follows, because asymmetric algorithms are far too slow to do that job.
This deep dive opens up all three algorithms in the title. We build AES and ChaCha20 from scratch in a few dozen lines of JavaScript, run RSA with numbers small enough to check by hand, and then measure what each costs. Every code example was run before publishing: the from-scratch ciphers were checked against the official test vectors and against OpenSSL on thousands of random inputs. For the practical side (writing production encryption code), see the companion article, Symmetric Encryption in JavaScript.
The short answer#
Two kinds of key#
Symmetric (AES, ChaCha20)
One secret key. Whoever can encrypt can also decrypt, so both sides must already share it and keep it secret.
Asymmetric (RSA, X25519)
A key pair. The public key can be given to anyone and only encrypts; the private key never leaves its owner and decrypts.
For most of history, all encryption was symmetric, and the hard part was getting the key to the other side: a courier with a codebook, a key distributed in advance. With n people who all want to talk privately, you need a separate key for every pair, which is n(n − 1)/2 keys: almost 5,000 for 100 people.
In 1976, Whitfield Diffie and Martin Hellman published a way for two parties to agree on a secret over a public channel. A year later, Ron Rivest, Adi Shamir and Leonard Adleman published RSA, the first practical public-key encryption and signature scheme. (Clifford Cocks at the UK’s GCHQ had found essentially the same idea in 1973, but it stayed classified until 1997.) With public keys, each person needs only one key pair, and the public half can be published openly.
Inside AES#
AES, originally called Rijndael and designed by Joan Daemen and Vincent Rijmen, won a public NIST competition in 2000 and became a federal standard (FIPS 197) in 2001. It’s a block cipher: a keyed permutation that turns 16 bytes into 16 different-looking bytes. On its own, it encrypts exactly one block; modes such as GCM turn it into something that can encrypt messages of any length.
AES treats the block as a 4×4 grid of bytes and runs 10, 12 or 14 rounds for 128-, 192- or 256-bit keys. Each round applies four simple steps:
- SubBytes replaces each byte using a fixed table, the S-box. It’s the only non-linear step, and without it AES could be solved like a system of linear equations.
- ShiftRows rotates row r of the grid left by r places, so each column’s bytes get spread across different columns.
- MixColumns multiplies each column by a fixed matrix, so every byte in a column affects all four. (It’s skipped in the last round, where it would add nothing.)
- AddRoundKey XORs in a round key, derived from the main key by the key schedule. This is the only step that uses the key.
That’s the whole algorithm. Here it is for 128-bit keys:
// aes128.mjs: AES-128 encryption of one 16-byte block, written out step by step (FIPS 197).
// For learning only. Real code should use Web Crypto, which is faster and safe against timing attacks.
const xtime = (b) => ((b << 1) ^ (b & 0x80 ? 0x1b : 0)) & 0xff; // multiply by 2 in GF(2^8)
const rotl8 = (x, n) => ((x << n) | (x >> (8 - n))) & 0xff;
// The S-box: each byte's inverse in GF(2^8), then a fixed affine transform. Computed here instead of a table.
const SBOX = new Uint8Array(256);
for (let p = 1, q = 1, first = true; first || p !== 1; first = false) {
p = (p ^ (p << 1) ^ (p & 0x80 ? 0x1b : 0)) & 0xff; // p * 3
q ^= q << 1; q ^= q << 2; q ^= q << 4; q &= 0xff; // q / 3
if (q & 0x80) q ^= 0x09;
SBOX[p] = q ^ rotl8(q, 1) ^ rotl8(q, 2) ^ rotl8(q, 3) ^ rotl8(q, 4) ^ 0x63;
}
SBOX[0] = 0x63;
// Key expansion: the 16-byte key becomes 11 round keys (176 bytes).
function expandKey(key) {
const w = new Uint8Array(176);
w.set(key);
for (let i = 16, rcon = 1; i < 176; i += 4) {
let t = w.slice(i - 4, i);
if (i % 16 === 0) {
t = Uint8Array.of(SBOX[t[1]] ^ rcon, SBOX[t[2]], SBOX[t[3]], SBOX[t[0]]);
rcon = xtime(rcon);
}
for (let j = 0; j < 4; j++) w[i + j] = w[i - 16 + j] ^ t[j];
}
return w;
}
// MixColumns: each 4-byte column is multiplied by a fixed matrix, so every byte affects all four.
function mixColumns(s) {
const out = new Uint8Array(16);
for (let c = 0; c < 16; c += 4) {
const [a0, a1, a2, a3] = s.subarray(c, c + 4);
const all = a0 ^ a1 ^ a2 ^ a3;
out[c] = a0 ^ all ^ xtime(a0 ^ a1);
out[c + 1] = a1 ^ all ^ xtime(a1 ^ a2);
out[c + 2] = a2 ^ all ^ xtime(a2 ^ a3);
out[c + 3] = a3 ^ all ^ xtime(a3 ^ a0);
}
return out;
}
export function encryptBlock(key, block) {
const w = expandKey(key);
let s = block.map((b, i) => b ^ w[i]); // AddRoundKey with the original key
for (let round = 1; round <= 10; round++) {
s = s.map((b) => SBOX[b]); // SubBytes: the only non-linear step
s = s.map((_, i) => s[(i + 4 * (i % 4)) % 16]); // ShiftRows: row r rotates left by r
if (round < 10) s = mixColumns(s); // MixColumns (not in the last round)
s = s.map((b, i) => b ^ w[16 * round + i]); // AddRoundKey
}
return s;
}And checked against the example in the standard itself:
import { encryptBlock } from "./aes128.mjs";
const hex = (s) => Uint8Array.from(s.match(/../g), (h) => parseInt(h, 16));
const toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
const key = hex("000102030405060708090a0b0c0d0e0f");
const block = hex("00112233445566778899aabbccddeeff");
console.log(toHex(encryptBlock(key, block)));
// 69c4e0d86a7b0430d8cdb78070b4c55a: the test vector in FIPS 197, appendix C.1Our test harness also compared it with OpenSSL on 2,000 random keys and blocks, and every result matched. It also measured the property that makes AES work: the avalanche effect. Flipping a single input bit changed on average 64.1 of the 128 output bits, which is exactly what you’d expect from a random permutation.
Inside ChaCha20#
ChaCha20 was designed by Daniel Bernstein in 2008, as a refinement of his earlier Salsa20, and standardized with the Poly1305 authenticator in RFC 8439. It’s a stream cipher: instead of transforming the data, it generates a stream of pseudorandom bytes from the key and nonce, and XORs that stream with the data. Decryption does the same XOR again.
Its internal state is 16 32-bit words, filled like this:
The ChaCha20 state: 16 words of 32 bits
The only operation is the quarter round, which mixes four words using nothing but addition, rotation and XOR (“ARX”). ChaCha20 applies it to the columns of the grid, then to its diagonals, ten times over for 20 rounds, and finally adds the original state back in so the steps can’t simply be run backwards:
// chacha20.mjs: the ChaCha20 block function (RFC 8439). For learning only.
const rotl = (x, n) => ((x << n) | (x >>> (32 - n))) >>> 0;
// The quarter round: only Add, Rotate and XOR on 32-bit words ("ARX").
export function quarterRound(a, b, c, d) {
a = (a + b) >>> 0; d = rotl(d ^ a, 16);
c = (c + d) >>> 0; b = rotl(b ^ c, 12);
a = (a + b) >>> 0; d = rotl(d ^ a, 8);
c = (c + d) >>> 0; b = rotl(b ^ c, 7);
return [a, b, c, d];
}
// One block: 64 bytes of keystream from a 32-byte key, a 32-bit block counter and a 12-byte nonce.
export function chachaBlock(key, counter, nonce) {
const words = (bytes) => Array.from({ length: bytes.length / 4 }, (_, i) => new DataView(bytes.buffer, bytes.byteOffset).getUint32(4 * i, true));
const init = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574, ...words(key), counter, ...words(nonce)]; // "expand 32-byte k"
const x = init.slice();
const qr = (a, b, c, d) => ([x[a], x[b], x[c], x[d]] = quarterRound(x[a], x[b], x[c], x[d]));
for (let i = 0; i < 10; i++) { // 20 rounds, done as 10 "double rounds"
qr(0, 4, 8, 12); qr(1, 5, 9, 13); qr(2, 6, 10, 14); qr(3, 7, 11, 15); // columns
qr(0, 5, 10, 15); qr(1, 6, 11, 12); qr(2, 7, 8, 13); qr(3, 4, 9, 14); // diagonals
}
const out = new DataView(new ArrayBuffer(64));
x.forEach((v, i) => out.setUint32(4 * i, (v + init[i]) >>> 0, true)); // add the input back in
return new Uint8Array(out.buffer);
}
console.log(quarterRound(0x11111111, 0x01020304, 0x9b8d6f43, 0x01234567).map((w) => w.toString(16)));
// [ 'ea2a92f4', 'cb1cf8ce', '4581472e', '5881c4bb' ]: the test vector in RFC 8439, section 2.1.1Besides the quarter-round vector above, our version matched RFC 8439’s full-block test vector and OpenSSL’s keystream for 500 random keys, nonces and counters.
ARX is why ChaCha20 is fast in plain software and naturally resistant to timing attacks: additions, rotations and XORs take the same time whatever the values, and there are no tables to leak through the cache. That makes it the usual choice on devices without AES instructions. Each 64-byte block is also computed independently from its counter, so blocks can be generated in parallel or out of order.
Neither AES nor ChaCha20 detects tampering on its own. In practice they’re used as AES-GCM and ChaCha20-Poly1305, which add a 16-byte authentication tag.
Inside RSA#
RSA is built on modular arithmetic. Pick two large secret primes p and q, and publish their product n. Encrypting raises the message to a public power e, modulo n. Decrypting raises the result to a private power d, which undoes it. Computing d requires knowing p and q, and finding them from n means factoring a number hundreds of digits long, which nobody knows how to do efficiently. Here it is with the classic textbook numbers:
// RSA with tiny numbers, to show the math. Real keys use primes of 1,536 bits or more, and padding.
const modPow = (base, exp, mod) => {
let result = 1n;
for (base %= mod; exp > 0n; exp >>= 1n, base = (base * base) % mod) if (exp & 1n) result = (result * base) % mod;
return result;
};
const p = 61n, q = 53n; // two secret primes
const n = p * q; // 3233: the modulus, part of the public key
const phi = (p - 1n) * (q - 1n); // 3120: computable only if you know p and q
const e = 17n; // the public exponent
const d = 2753n; // the private exponent, chosen so that e * d leaves remainder 1 when divided by phi
console.log((e * d) % phi); // 1n
const m = 65n; // the message, as a number smaller than n
const c = modPow(m, e, n); // encrypt with the public key (e, n)
console.log(c); // 2790n
console.log(modPow(c, d, n)); // 65n: decrypt with the private key (d, n)
// Why real RSA needs padding:
console.log(modPow(65n, e, n) === c); // true: anyone can encrypt guesses and compare
const doubled = (c * modPow(2n, e, n)) % n; // an attacker changes the ciphertext without knowing m...
console.log(modPow(doubled, d, n)); // 130n: ...and the hidden message doublesReal keys use the same math with a modulus of 2,048 bits or more. The largest RSA number factored publicly is RSA-250, at 829 bits, in 2020, which took about 2,700 CPU core-years.
The last lines of the example show why “textbook” RSA is never used directly. It’s deterministic, so an attacker can encrypt likely messages (“yes”, “no”, a salary figure) and compare. And it’s malleable: multiplying a ciphertext by an encrypted number multiplies the hidden message, without knowing either. Real RSA encryption therefore pads the message with structured randomness before encrypting.
- OAEP (Optimal Asymmetric Encryption Padding, PKCS #1 v2) is the padding to use, and the only one Web Crypto offers for encryption.
- PKCS #1 v1.5 padding is the older scheme. In 1998, Daniel Bleichenbacher showed that a server revealing whether the padding of a ciphertext was valid lets an attacker decrypt messages, and the 2017 ROBOT study found the same flaw still present in many servers. Avoid it for encryption.
With Web Crypto, RSA-OAEP looks like this:
// RSA-OAEP with Web Crypto: a 3072-bit key (128-bit security), SHA-256, the standard exponent 65537.
const { publicKey, privateKey } = await crypto.subtle.generateKey(
{ name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
false, // the private key can't be exported; the public key always can
["encrypt", "decrypt"],
);
const secret = new TextEncoder().encode("a short secret");
const c1 = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, publicKey, secret));
const c2 = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, publicKey, secret));
console.log(c1.length); // 384: always the size of the modulus, however short the message
console.log(c1.some((b, i) => b !== c2[i])); // true: OAEP adds randomness, so equal messages look different
console.log(new TextDecoder().decode(await crypto.subtle.decrypt({ name: "RSA-OAEP" }, privateKey, c1))); // a short secret
// The most it can encrypt is the key size minus 66 bytes: 318 bytes here.
await crypto.subtle.encrypt({ name: "RSA-OAEP" }, publicKey, new Uint8Array(319)).catch((e) => console.log(e.name)); // OperationErrorThe size limit is the important part. OAEP with SHA-256 takes 66 bytes of each block, so RSA can encrypt at most 190 bytes with a 2,048-bit key, 318 with a 3,072-bit key, and 446 with a 4,096-bit key (all three confirmed in our tests). That’s enough for a key, not for a document.
The same key pair can also sign: the owner uses the private key to produce a value that anyone can check with the public key. Signing proves who sent something; encryption keeps it secret. In fact, most RSA in use today signs rather than encrypts, for example in the certificates that identify websites, and in JWTs signed with RS256.
Side by side#
| AES | ChaCha20 | RSA | |
|---|---|---|---|
| Type | Symmetric block cipher | Symmetric stream cipher | Asymmetric (public key) |
| Built from | Substitution and permutation rounds | Add, rotate, XOR rounds | Modular exponentiation; hard because factoring is |
| Key for 128-bit security | 128 bits (256 common) | 256 bits (the standard size) | 3,072 bits |
| Encrypts | Any amount (with a mode such as GCM) | Any amount | Up to 318 bytes with a 3,072-bit key |
| Output size | Same as the input, plus nonce and tag | Same as the input, plus nonce and tag | Always the key size (384 bytes for 3,072 bits) |
| Main use today | Bulk data, storage, TLS | Bulk data, TLS, mobile, VPNs (WireGuard) | Signatures and certificates; wrapping keys |
| Large quantum computer | Weakened, not broken | Weakened, not broken | Broken |
How much slower is asymmetric?#
We timed single operations with node:crypto in Node.js 24 (Docker Desktop, 32 CPUs, 32 GB), in two runs that agreed closely:
| Operation | Time |
|---|---|
| AES-256-GCM: encrypt 32 bytes | 4 µs |
| ChaCha20-Poly1305: encrypt 32 bytes | 4 µs |
| RSA-2048 OAEP: encrypt 32 bytes (public key) | 19 µs |
| RSA-2048 OAEP: decrypt (private key) | 0.37 ms |
| RSA-3072 OAEP: encrypt 32 bytes (public key) | 33 µs |
| RSA-3072 OAEP: decrypt (private key) | 1.1 ms |
| RSA-4096 OAEP: decrypt (private key) | 2.5 ms |
| RSA-2048 / 3072 / 4096: generate a key pair | 30 ms / 83 ms / 290–360 ms |
| X25519: compute a shared secret | 22 µs |
| RSA-3072: sign / verify | 1.1 ms / 29 µs |
| Ed25519: sign / verify | 24 µs / 65 µs |
- RSA’s private-key operations are the expensive ones. Decrypting with a 3,072-bit key took about 270 times as long as an AES-GCM encryption. Per byte the gap is far larger: in the companion article, AES-GCM encrypted over 1,200 MiB per second on the same machine, while RSA-3072 can decrypt 318 bytes per 1.1 ms, about 0.3 MiB per second. That’s more than 4,000 times slower.
- Public-key operations are cheap because e is small (65,537), while d is as large as the modulus. That’s why RSA signatures are slow to make but fast to check.
- Cost grows steeply with key size. Going from 2,048 to 4,096 bits made decryption about 7 times slower and key generation 10 to 12 times slower. (Generating a key means searching for random primes, so its time varies from run to run.)
- Elliptic curves are much cheaper. An X25519 key agreement took 22 µs, about 50 times faster than one RSA-3072 decryption, with 32-byte public keys instead of 422 bytes.
Hybrid encryption#
Since RSA can only encrypt a few hundred bytes, and slowly, it never encrypts the data itself. Instead, it encrypts a symmetric key:
- 1Make a one-time keyGenerate a random 256-bit AES key for this message only.
- 2Encrypt the dataAES-GCM encrypts the message, of any size, with that key.
- 3Wrap the keyRSA-OAEP encrypts the 32-byte AES key with the recipient’s public key.
- 4Send bothThe wrapped key, the nonce, and the AES ciphertext travel together.
- 5Unwrap and decryptThe recipient’s private key recovers the AES key, which decrypts the data.
Web Crypto has wrapKey and unwrapKey for exactly this, so the AES key never has to appear as raw bytes in your code:
// hybrid.mjs: encrypt any amount of data for whoever holds an RSA private key.
// AES-GCM encrypts the data; RSA-OAEP encrypts ("wraps") only the random AES key.
export async function seal(publicKey, data) {
const aesKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt"]);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, aesKey, data));
const wrappedKey = new Uint8Array(await crypto.subtle.wrapKey("raw", aesKey, publicKey, { name: "RSA-OAEP" }));
return { wrappedKey, iv, ciphertext };
}
export async function open(privateKey, { wrappedKey, iv, ciphertext }) {
const aesKey = await crypto.subtle.unwrapKey(
"raw", wrappedKey, privateKey, { name: "RSA-OAEP" }, { name: "AES-GCM" }, false, ["decrypt"],
);
return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, aesKey, ciphertext));
}import { seal, open } from "./hybrid.mjs";
const { publicKey, privateKey } = await crypto.subtle.generateKey(
{ name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
false,
["wrapKey", "unwrapKey"],
);
const report = new Uint8Array(5_000_000); // 5 MB: far beyond what RSA could encrypt directly
const sealed = await seal(publicKey, report);
console.log(sealed.wrappedKey.length, sealed.ciphertext.length - report.length); // 384 16: the whole overhead
console.log((await open(privateKey, sealed)).length); // 5000000The asymmetric part costs the same 384 bytes and roughly a millisecond whether the message is 5 bytes or 5 gigabytes. In our tests, changing the ciphertext, changing the wrapped key, or using the wrong private key all made open() fail, and Python’s cryptography library opened a message sealed by this code, so the format is standard.
This is how most “public-key encryption” actually works. A JWE token with RSA-OAEP-256 and A256GCM is this exact construction, and our JWE tool shows its parts. PGP and S/MIME email encryption work the same way, as does HPKE (RFC 9180), the modern standard for it, which replaces the RSA step with an elliptic-curve key agreement.
Key agreement: why TLS 1.3 dropped RSA encryption#
Until TLS 1.2, a common way to start an HTTPS connection was for the browser to make a random key and encrypt it with the RSA public key in the server’s certificate. It worked, but it had a serious weakness: anyone who recorded the encrypted traffic and later obtained the server’s private key (by a breach, a court order, or a careless backup) could decrypt every recorded session, going back years.
Key agreement avoids that. Both sides generate a temporary key pair for each connection, exchange public keys, and each combines its own private key with the other’s public key. They arrive at the same secret, which never crossed the network:
// x25519.mjs: two parties agree on an AES key without ever sending it (Web Crypto).
const alice = await crypto.subtle.generateKey({ name: "X25519" }, false, ["deriveBits"]);
const bob = await crypto.subtle.generateKey({ name: "X25519" }, false, ["deriveBits"]);
// Only the 32-byte public keys are exchanged.
// Each side combines its own private key with the other's public key and gets the same secret...
const secretA = await crypto.subtle.deriveBits({ name: "X25519", public: bob.publicKey }, alice.privateKey, 256);
const secretB = await crypto.subtle.deriveBits({ name: "X25519", public: alice.publicKey }, bob.privateKey, 256);
// ...which goes through HKDF to become the actual AES key. Never use the raw secret as a key.
async function aesKeyFrom(secret) {
const base = await crypto.subtle.importKey("raw", secret, "HKDF", false, ["deriveKey"]);
const info = new TextEncoder().encode("example-app v1 message key"); // binds the key to its purpose
return crypto.subtle.deriveKey(
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(32), info },
base,
{ name: "AES-GCM", length: 256 },
true, // extractable only so this demo can compare the two keys
["encrypt", "decrypt"],
);
}
const raw = async (k) => new Uint8Array(await crypto.subtle.exportKey("raw", k)).join();
console.log((await raw(await aesKeyFrom(secretA))) === (await raw(await aesKeyFrom(secretB)))); // trueBecause those temporary private keys are thrown away after the handshake, a later key theft reveals nothing about past sessions. This property is called forward secrecy. TLS 1.3 (RFC 8446) removed RSA key transport entirely, so every full handshake uses a fresh key agreement. The server’s long-term RSA or ECDSA key now only signs the handshake, to prove it’s really the server. X25519, used above, is one of the most widely used key agreements in TLS today.
Key sizes and security levels#
Symmetric and asymmetric keys can’t be compared bit for bit. A 128-bit AES key is attacked by trying keys, while an RSA modulus is attacked by factoring, which has much better shortcuts. NIST’s key management guidance (SP 800-57) gives these equivalents:
| Security level | Symmetric | RSA | Elliptic curve |
|---|---|---|---|
| 112 bits | (3DES, retired) | 2,048 bits | 224 bits |
| 128 bits | AES-128 | 3,072 bits | 256 bits (X25519, P-256) |
| 192 bits | AES-192 | 7,680 bits | 384 bits (P-384) |
| 256 bits | AES-256, ChaCha20 | 15,360 bits | 512 bits (P-521) |
RSA-2048 is still widely used and still allowed, but it gives 112-bit security, below the 128 bits of AES-128. For new RSA keys meant to last, 3,072 bits is the better default. The table also shows why elliptic curves took over: to match AES-256, RSA would need a 15,360-bit key.
What quantum computers change#
A large enough quantum computer, which doesn’t exist yet, would affect the two families very differently:
- Shor’s algorithm breaks RSA and elliptic curves completely, because it factors numbers and solves discrete logarithms efficiently. Bigger keys don’t help.
- Grover’s algorithm only weakens symmetric ciphers, in theory halving the effective key length. AES-256 and ChaCha20 would still have 128-bit security. AES-128 is generally considered fine in practice too, since Grover’s attack would need an impractically long sequential computation.
The worry today is “harvest now, decrypt later”: traffic recorded now could be decrypted once such a machine exists. That’s why the replacements are already being rolled out. NIST published ML-KEM (FIPS 203), a post-quantum key agreement, in August 2024, alongside post-quantum signatures. Chrome uses a hybrid of X25519 and ML-KEM for TLS by default, and OpenSSH has used a post-quantum hybrid key exchange by default since version 9.0. A NIST draft (IR 8547) proposes deprecating RSA and elliptic-curve algorithms at 112-bit security after 2030 and disallowing them after 2035.
Symmetric encryption needs no replacement: AES-256 and ChaCha20 stay. What changes is the asymmetric part that delivers their keys.
Which one to use#
FAQ#
Is asymmetric encryption more secure than symmetric?
No. Neither is “more secure”; they solve different problems. At equal security levels, both are equally hard to break today. Asymmetric cryptography exists because it solves key distribution, not because it’s stronger, and it’s the part quantum computers threaten.
Can I encrypt a file directly with RSA?
Not with standard padding: a 3,072-bit key encrypts at most 318 bytes. Splitting a file into RSA-sized pieces would be slow and is not a recognized secure scheme. Use hybrid encryption.
Why is RSA’s public exponent almost always 65,537?
65,537 is 216 + 1, so raising a number to that power takes only 17 multiplications, which makes encryption and signature checks fast. It’s large enough to avoid attacks that work with very small exponents such as 3.
Is ChaCha20 better than AES?
Neither is better in security. AES is faster on hardware with AES instructions, which most servers, laptops and modern phones have. ChaCha20 is faster in pure software and easier to implement without timing leaks. TLS 1.3 offers both, and clients pick based on their hardware.
Should I write my own AES or RSA, now that I’ve seen how?
No. The code here is correct, but our AES leaks timing through its table lookups, and our RSA has no padding and toy numbers. Production implementations handle those details and many more. Use Web Crypto, node:crypto, or a well-reviewed library, and keep this code for understanding what they do.
Try it in your browser
- Encrypt & Decrypt: try AES (in several modes) and ChaCha20-Poly1305 with a password or a raw key.
- JWE Decoder, Encoder & Editor: see hybrid encryption in a real format: RSA-OAEP or ECDH-ES for the key, AES-GCM for the content.