bilingual · en / pt
cryptography is a science of its own
I left a class on cryptography angry at how it was run, and went looking. It wasn't the subject that lost me: I was following well enough to notice the class drifting off topic and leaving wrong things behind on the way. This post is what I wish I had heard, written for someone who has never seen the math and for someone who already lives in it.
A note on scope: I am not a cryptographer. This whole post is the argument for why that sentence matters.
the question that stayed
Every developer uses cryptography every day. You opened this page over TLS, and if it asks for a password anywhere, there is a hash in the middle. It is the most universally used and least universally understood technology in our profession.
And the question that stuck with me was: why does nobody explain the concept before the acronym? You can sit through a full hour of WEP, WPA2, WPS, SSL, tokens and certificates and walk out unable to say what a key is. The acronym is the end of the story. Starting there is starting at the end.
So let's start at the beginning. And the beginning is a lot older than it sounds.
three thousand years of scrambling
The first cryptography we have a decent record of had no math in it at all. It was a stick.
The Spartans wrapped a strip of leather around a rod of a specific thickness and wrote the message along its length. Unwrapped, the strip was a pile of loose letters that meant nothing. To read it you needed a rod of the same thickness. They called it a scytale.
Notice what the thickness of the rod is in that story: it's the key. Nobody used the word, but the role is exactly that: the piece of information that separates who can read from who can't.
About six hundred years later, Caesar was doing something else. Instead of scrambling the position of the letters, he replaced each letter with another one, three places further down the alphabet. A becomes D, B becomes E, and so on until the alphabet wraps around.
Those two ideas, move the position and swap the symbol, are the basis of everything that came in the following three thousand years. The rest was refinement.
And the obvious refinement showed up fast: instead of shifting the alphabet by a fixed number, shuffle the whole thing. Every letter becomes some other letter, with no pattern. That gives a number of possible arrangements with twenty-six digits, which at the time looked like the end of the conversation.
It wasn't.
- 700 BCscytalesparta wraps the strip around the rod. the thickness is the key, and nobody yet has a word for that.
- 50 BCCaesar ciphersubstitution by fixed shift. twenty-five possible keys, which only becomes a problem once someone thinks to try them all.
- 850Al-Kindifrequency analysis in Baghdad. the first systematic method for breaking a cipher without holding the key.
- 1553Vigenèrethe polyalphabetic cipher that held for three centuries and earned the nickname le chiffre indéchiffrable.
- 1863Kasiskipublishes how to find the length of a Vigenère key by looking for repetitions. the unbreakable one breaks.
- 1883Kerckhoffsstates the principle that separates the algorithm from the key, and becomes the rule the field still follows.
There is one thing the scytale, the Caesar cipher and the shuffled substitution have in common, and it explains why all of them fell: in all three, the secret was the method. Anyone who worked out how the cipher operated could read everything ever written with it, forever.
Al-Kindi and the birth of cryptanalysis
In the ninth century, in Baghdad, a man named Al-Kindi wrote the text that is, to me, the real landmark of this whole post.
His idea is almost embarrassingly simple. In any language, letters don't appear with equal frequency. In English, E and T are everywhere; Q and Z barely show up. Under a substitution, a letter changes clothes but doesn't change frequency. If E becomes Q, then Q will appear in the ciphertext exactly as abundantly as E did in the original.
So you don't need the key. You count the letters.
That sounds small and it's enormous. It's the first systematic attack in history: a procedure anyone can follow, that depends on neither luck nor insight, and that works against an entire family of ciphers instead of one specific message.
Before Al-Kindi, breaking a cipher was talent. After him, it was method.
That's the border this post is named after. The moment a repeatable procedure for attacking exists, a criterion for judging defence exists too: you can say one cipher is better than another, and say why. That's science. The rest was craft.
And Al-Kindi is where cryptography picked up the habit it still has: nobody believes in a cipher because it looks good. They believe it after competent people have tried to break it and failed.
Kerckhoffs: security lives in the key
The Vigenère cipher was the answer to frequency analysis, and it was a good answer. Instead of one substitution alphabet, several, rotating according to a keyword. The same plaintext letter becomes different letters in different positions, and the frequency profile flattens out. For three hundred years it was known as le chiffre indéchiffrable.
In 1863, Kasiski published how to find the length of the keyword by looking for repeated stretches in the ciphertext. Once you have the length, the Vigenère falls apart into several Caesars, and each one dies to frequency analysis. Unbreakable for three centuries, broken in one paper.
Twenty years later, a Dutchman named Auguste Kerckhoffs wrote the sentence that organised the entire field.
A cryptographic system must stay secure even if everything about it is public, except the key. If your security depends on the enemy not knowing how your system works, you don't have security. You have a deadline.
This is less obvious than it sounds today. Kerckhoffs was telling people to give up the most intuitive advantage there is, which is the enemy not knowing what you're doing. And his argument is purely practical: methods leak. People leave teams, equipment gets captured, code gets read. You can change a key in an afternoon; you can't change a method.
That's why the algorithms protecting your bank are published on the internet, with open specifications, and it isn't an oversight. It's the design.
And this is where the rule that closes this post comes from, the one about never inventing your own cryptography. It isn't the conservatism of a field. It's the direct consequence of Kerckhoffs: if security has to live in the key and not in the secrecy of the method, then the method needs to have been read by a lot of people. An algorithm nobody has examined isn't secret. It's just unknown.
one key, or two
Symmetric cryptography is the intuitive idea, the one you already had as a kid: both ends agree on a secret and use it to scramble and unscramble. One key, on both sides.
It's fast, and it's what protects the bulk of your data today: AES is symmetric. But it has a problem that sounds silly and is fatal: how do the two ends agree on the key? If I need a secure channel to send you the key, and the key is exactly what creates the secure channel, I'm walking in a circle.
Asymmetric cryptography breaks that circle. Instead of one key, a pair, bound by math: what one closes, only the other opens. One of them you publish to the entire world. The other never leaves your machine.
symmetric
- one key, both sideswhoever encrypts and whoever decrypts hold exactly the same secret.
- fast
- but how do you agree on it?
asymmetric
- a pair of keystwo keys bound by math: what one closes, only the other opens.
- one of them is public
- breaks the circle, and is slow
The part that feels like magic is that publishing one key doesn't give away the other. That rests on math problems that are easy in one direction and absurdly hard in reverse: multiplying two huge primes is trivial, factoring the result back apart is not.
Except this idea is far newer than the rest of this post makes it sound.
Diffie-Hellman and RSA
For three thousand years, the answer to "how do the two ends agree on the key" was always the same: somebody carries it. A courier, a meeting, a briefcase. Cryptography protected the message and outsourced the key problem to logistics.
That worked because the users were governments and armies, and armies have couriers. Once civilian communication started to grow, it stopped working. You can't send a courier for every pair of people who might want to talk, and the number of keys you need grows with the square of the number of participants.
In 1976, Whitfield Diffie and Martin Hellman published a paper showing that two strangers can arrive at a shared secret by talking in public, in front of whoever is listening, without ever saying the secret out loud.
It's worth stopping on that, because it sounds impossible. It isn't a clever way of hiding the key while it's in transit. It's that the key is never sent. Each side combines what it received with something only it knows, and both arrive at the same result by different routes. Whoever listened to the whole conversation holds both public halves and still can't get there.
The following year, Ron Rivest, Adi Shamir and Leonard Adleman published RSA, which takes the next step: beyond agreeing on a key, you can have a permanent pair with one publishable half. That's what finally separates "who can write to me" from "who can read what was written to me".
You can watch it work with small numbers. Pick two primes, and both keys fall out of them:
- n = p·q
- 143
- φ(n) = (p−1)(q−1)
- 120
- public key (e, n)
- (7, 143)
- private key (d, n)
- (103, 143)
- encrypted m^e mod n
- 81
- decrypted c^d mod n
- 42
Two footnotes that I think are worth more than footnotes.
The first is that the British government already had this. James Ellis, Clifford Cocks and Malcolm Williamson reached the same ideas at GCHQ a few years earlier, and it stayed classified until 1997. Discovered first, useless for two decades, because nobody was allowed to use it.
The second is that RSA from 1977 is still standing in 2026. Forty-nine years of very good people trying to break it, in public, and what pushed key sizes up was hardware getting faster, not the math giving way. That's what "tested by time" means in practice.
the digital signature
There's a use of the key pair that almost never gets explained properly, and it's half the reason the internet works.
So far the pair has been used to hide: you encrypt with someone's public key, and only their private key opens it. Now reverse the order. Encrypt with your private key, and anyone can open it with your public one.
That sounds useless, because if anyone can open it there's no secret. And there isn't. There isn't meant to be. What it proves is authorship: if it opened with your public key, it can only have been closed with your private one, which only you hold.
In practice nobody signs the whole message, because it would be slow. You sign its hash, small, fixed-size, and completely different if anyone touches a byte of the original. That's why signatures and hashes always travel together, and why a broken hash breaks the signatures with it.
And that's what a website's certificate does. It hides nothing. It's a statement signed by someone your browser already trusts, saying that this public key belongs to that domain. Encrypting perfectly with the wrong impostor is still a useless victory.
A1, A3 and the token
This section exists for a specific reason: this is what the class name-dropped without explaining, and it's the kind of thing that sounds like advanced cryptography when it isn't.
A1 and A3 are types of digital certificate under the Brazilian standard. The difference between them isn't the algorithm, isn't the key size, isn't the math. It's where the private key lives.
In A1, the private key is a file. You install it on the computer, and it can be copied, moved, backed up, attached to an email by mistake. It's convenient and it's fragile for the same reason.
In A3, the private key is generated inside a USB token or smartcard and never leaves. You don't send the key to the document; you send the document to the device, it signs internally and hands back only the signature. Even with the machine compromised, an attacker can request signatures while the token is plugged in, but can't walk away with the key.
It's the same difference between keeping your house key in your pocket and leaving it in a lock that only works while you're standing there.
And the "token" from the class, which turned up in the same sentence as though it were a third algorithm, is this: a piece of hardware. A possession factor, not a cryptographic primitive. Worse, the word is overloaded: an auth token in an API is something else entirely, a signed string the server issues. Same word, two worlds, and putting both in a list of acronyms is exactly how people learn it wrong.
a hash is not a cipher
This is where most people get lost, and the confusion has practical consequences.
Encrypting is a two-way street: there is a key that undoes it. Hashing is one-way. It takes input of any size and returns a fixed-size summary, and no key undoes it, because there is no information left to undo. When a site says it doesn't know your password, that's what it means: it stored the hash, not the password.
A good hash has a property that's easier to see than to explain. Change one letter of the input, just one, and the entire output becomes something else, with no resemblance to what came before. It's called the avalanche effect:
same text, one letter flipped: Cryptography
and the opposite of that, when a hash fails: two different PDFs with the same SHA-1, published in 2017 by Google and CWI. recorded values, the browser does not recompute SHA-1 here.
shattered-1.pdfshattered-2.pdfThat's what stops anyone from creeping toward the answer by guided trial and error: there is no "almost right". Either it's the same hash, or there is no information at all in how wrong you were.
And this is where the acronyms finally earn their place, because hashing is somewhere things die. MD5 fell: practical collisions since 2004, two different inputs with the same summary, produced on purpose. SHA-1 fell in 2017, when researchers at Google and CWI published two different PDFs with the same SHA-1. Both still show up in production systems today. SHA-256 is the de facto standard now.
Password hashing is its own case: plain SHA-256 is too fast for it, and speed is exactly what helps whoever is guessing. Passwords need a deliberately slow, salted function: bcrypt, scrypt, Argon2, PBKDF2.
the padlock in the address bar
With keys and hashes in hand, TLS stops being an acronym and becomes a story with a beginning, a middle and an end. And it answers the question left hanging above: if asymmetric is slow and symmetric can't agree on a key, how does the internet work at all?
It works because the two take turns.
the browser says which ciphers it speaks and already sends its public share of the key agreement.
The detail that almost always disappears from the explanation: the shared secret never crosses the network. Each side sends one public half and computes the same result alone. Anyone listening on the wire sees both halves and cannot get to the result.
And the certificate has nothing to do with scrambling data. It answers a different question, which is "who am I talking to anyway". Encrypting flawlessly with the wrong impostor is a useless victory.
About "SSL": the name is dead. SSL 3.0 was retired in 2015, and what runs today is TLS, preferably 1.3. The nickname stuck out of inertia, like still calling a car a motorcar.
the wi-fi that fell four times
Wi-fi is the best cryptography case study there is, because its entire history is public and it repeats: someone publishes a standard, someone breaks it, the standard gets replaced.
- 1997WEPreused RC4's initialization vector. broken in 2001; today it falls in minutes.
- 2003WPAan emergency patch (TKIP) to run on hardware that already existed. it was always meant to be temporary.
- 2004WPA2real AES. it held for thirteen years, until KRACK in 2017 attacked the negotiation, not the cipher.
- 2006WPSthe easy-connect button. its eight-digit PIN could be guessed in halves, and it fell in 2011. turn it off.
- 2018WPA3replaces the negotiation with a handshake that leaks no material for offline attack. Dragonblood, in 2019, found implementation flaws, not flaws in the idea.
Notice the pattern: WEP died because the math was wrong. WPA2 and WPA3 took their hits through implementation and negotiation. That's the most important distinction in this whole post, and it comes back at the end.
Turing, the hinge
Here the story turns, and it turns on a single point.
Enigma is the most retold piece of cryptography in computing, so I won't retell the film. But the mechanism of the attack is worth telling, because it's the part that matters for the rest of this section.
Enigma had a configuration space large enough to be infeasible to test one by one, even today. What Bletchley Park exploited wasn't brute force: it was structure. The machine had a property that looked harmless: no letter could ever encrypt to itself. Which means that if you guess a message contains a likely word, you can slide that word along the ciphertext and discard every position where some letter lines up with itself.
Those likely words were called cribs, and they came from habit: weather reports sent at the same hour, protocol greetings, messages that always ended the same way. The electromechanical bombe then tested configurations against what was left, and each logical contradiction eliminated a whole block of possibilities at once.
In other words: the full space was never tested. Statistical regularity and prior knowledge of the likely content were used to prune it down to something a machine of that era could walk through.
Hold on to that paragraph, because it comes back shortly under a different name.
And here is the coincidence that isn't one: the man who led that effort is the same man who, twelve years later, wrote "Computing Machinery and Intelligence", the paper that opens with "can machines think" and proposes the test that carries his name.
Cryptography and artificial intelligence came out of the same head, a few years apart.
And it isn't a biographical accident. Reread the description of the attack on Enigma with the vocabulary swapped: intractable search space, pruning by constraint, statistical structure of language, a hypothesis about likely content. That's a description of machine learning written thirty years before the term existed. Both fields were born from the same question: what can a machine infer from what it was never told.
After that they separated, and spent seventy years barely speaking.
cypherpunks, crypto wars and blockchain
There's a chunk of this history that rarely makes it into a class, and it's the chunk that explains why you have cryptography in your pocket.
Until the seventies, strong cryptography belonged to states. What Diffie, Hellman and RSA did was take it out of government hands and put it in a published paper, and the reaction was exactly what you'd expect.
In the United States, cryptography above a certain key size was classified as munitions for export purposes. The same list as tanks and missiles. Exporting software with strong cryptography was, in the letter of the law, arms trafficking.
In 1991, Phil Zimmermann released PGP, which handed military-grade cryptography to anyone with a computer. He spent three years under federal criminal investigation, because the program left the United States over the internet. The defence was a stroke of genius: the source code was published as a book, printed, by MIT Press. Exporting weapons is a crime; exporting a book is protected speech under the First Amendment. The case was dropped in 1996.
In the same spirit, people walked around in t-shirts printed with four lines of Perl implementing RSA, with a warning that the shirt was, technically, a controlled export munition. It was a joke and a real piece of litigation at the same time.
Behind all of this was a mailing list, started in 1992, where these people organised. Eric Hughes wrote the line in the group's manifesto that sums up the method: cypherpunks write code. The idea was that speech protects nobody and law changes with elections. What protects you is software that exists, runs, and is published.
- 1976Diffie-Hellmantwo strangers agree on a secret in public. cryptography leaves the state monopoly and enters a journal.
- 1977RSAthe permanent key pair. forty-nine years later, still standing.
- 1991PGPZimmermann publishes, and spends three years under federal investigation for exporting munitions.
- 1993cypherpunk manifestocypherpunks write code. the thesis that published software protects more than legislation does.
- 2001AESthe end of the argument: a standard chosen by a five-year public competition, with everyone attacking the candidates in the open.
- 2008Bitcoinhash, signature and proof of work assembled differently. no new primitive.
Bitcoin is the one I find most interesting to look at from this angle, because it usually gets told as a technological rupture and it isn't. The 2008 paper invents no cryptography at all. You've seen hashing here, and digital signatures too, and proof of work dates to 1997, built to fight spam. The originality is entirely in the arrangement, in using those three pieces to settle the order of events with nobody at the centre.
Which is this post's rule showing up again by another route. The most disruptive thing applied cryptography has produced in two decades was built exclusively from old, audited parts. The people who invented new primitives inside blockchain projects, and there were plenty, supplied the examples of what not to do.
Hacker culture enters this story as the force that pushed cryptography out to the public, and its instinct is the same as Kerckhoffs's: open the code, publish the method, let the whole world try to break it. Coming from opposite directions, a nineteenth-century Dutch professor and an anarchist mailing list from the nineties, the two land on the same conclusion. A secret method is debt. Public scrutiny is the only asset.
the two priesthoods
This is where I get to what made me write.
Cryptography is not a topic inside information security, which is in turn a topic inside IT. It's an entire science, with its own math, its own conferences, and people who spend whole careers inside a single primitive. Using TLS is not knowing cryptography, the same way calling model.predict() is not knowing machine learning.
And the two fields, born together, now hold opposite cultures about time.
Cryptography has a rule everyone repeats: don't roll your own. A new algorithm is worth nothing for being elegant. It's worth something after years of competent people publicly trying to break it and failing. AES became the standard after a five-year open competition. Post-quantum cryptography took eight years of public process before it became a norm.
AI today publishes the paper in two weeks and ships it in the third.
I'm not saying one is right and the other is wrong. I'm saying both are depth, not surface, and only one of them is being treated as if it were surface.
where they meet again
And after seventy years, they have started touching again. On three fronts.
The first is the most concrete: deep learning became a side-channel attack tool. Instead of attacking the math of AES, you measure the chip's power consumption while it encrypts and train a network to infer the key from that trace. This is a mature area, with a reference dataset and its own metric, and the model's advantage is needing far fewer measurements than the old statistical methods.
The second is AI as the target: when you put a cipher inside a neural network, the network starts answering inputs the cipher would never accept, and that opens a door. EUROCRYPT 2026 carried exactly that kind of cryptanalysis of such constructions.
The third is the quantum clock. Shor's algorithm, from 1994, showed that a large enough quantum computer breaks RSA and elliptic curve, that is, nearly all asymmetric crypto in use. Nobody has that machine today, but the attack doesn't need it yet: it's enough to record today's encrypted traffic and wait. That's why migration has already started.
- 1994Shor's algorithmshows that a large enough quantum computer factors large numbers, taking RSA and elliptic curve down with it.
- 2016NIST opens the calla public process to pick the replacements. eight years of open analysis ahead.
- 2024-08the standards landML-KEM (FIPS 203) for key agreement, ML-DSA (FIPS 204) and SLH-DSA (FIPS 205) for signatures.
- 2025-03HQC as backupa second key mechanism, on different math, so the bet isn't entirely on lattices.
- 2030a real deadlineCNSA 2.0 requires national security systems to have migrated, and NIST deprecates the 112-bit level.
- 2035disallowedwhatever stayed behind stops being accepted.
And the warning missing from nearly every headline: AI does not break AES. Nothing on those three fronts scratches the math of a modern cipher. What AI attacks is the implementation, the physical leak, and the border between model and cipher. It's the exact lesson of WPA2.
what I have broken myself
It would be bad form to write all of this without saying where I got it wrong myself. All four are from my own code, in production, and all four were fixed.
The first is my favourite because it's almost poetic. I had a constant declaring a fifteen-minute lifetime for the access token, sitting neatly at the top of the file. And it was never passed to the function that signed the token. The result was that tokens came out with no expiry field at all, meaning they never expired. The code said fifteen minutes. The system delivered eternity. Today it rejects any token that arrives without a deadline, instead of trusting that the deadline was set.
The second isn't cryptography, it's what surrounds it, and it's worse. I had a function checking a user's role before allowing an admin route. It was registered with the wrong framework scope, one word, and because of that it didn't apply outside the file where it was declared. Nine permission checks became decoration. Any authenticated user could reach admin routes. The code looked right, reviewed well, and did absolutely nothing.
The third is the opposite: it went well. I had a file download endpoint that was public and built its path by concatenating whatever came in the URL, no authentication, no signature, and no check that the path stayed inside the folder. Anyone who guessed a name downloaded the file, and a run of ../ escaped the folder entirely. The replacement was an HMAC-signed URL over the key and the deadline, constant-time comparison, and the path resolved and checked against the root. One detail I only understood while writing it: the signature is verified before the expiry, on purpose. If I checked validity first, the difference between "invalid signature" and "expired link" would tell anyone probing that their signature was good.
The fourth is the same HMAC with a different threat model: a payment webhook. The provider signs every notification, and my side recomputes the signature, compares in constant time, and rejects anything outside a five-minute window, so nobody can replay a captured legitimate notification. And the rule that's worth more than all the cryptography: the webhook body never decides anything. It's a nudge for me to go ask the provider's API for the status, which is the only source of truth.
Those four share one moral, and it's WPA2's moral: the math failed in none of them. What failed was everything around it: a constant that never reached its destination, one scope keyword, an unvalidated path, an order of checks. It's always the seam.
what I took from a bad class
That cryptography is a science of its own, and that this is no excuse for not understanding the basics. It's the reason to respect them.
I'm not going to become a cryptographer. Nobody needs to. But knowing what a key is, why a hash doesn't come back, and where asymmetric hands the baton to symmetric is the difference between using the tool and being used by it. And knowing there is an entire science behind it is what stops you from rolling your own, which is, in the end, the only rule cryptography really asks of those standing outside it.
Saí de uma aula sobre criptografia revoltado com a condução dela, e fui atrás. Não foi o assunto que me perdeu: eu acompanhava o suficiente pra perceber que a aula tangenciava o tema e deixava coisa errada pelo caminho. Esse post é o que eu queria ter ouvido, escrito pra quem nunca viu a matemática e pra quem já vive nisso.
Aviso de escopo: eu não sou criptógrafo. Esse post inteiro é a defesa de por que essa frase importa.
a pergunta que sobrou
Todo dev usa criptografia todo dia. Você abriu essa página por TLS, e se ela pede senha em algum lugar, tem hash no meio. É a tecnologia mais universalmente usada e menos universalmente entendida que existe na nossa profissão.
E a pergunta que ficou pra mim foi: por que ninguém explica o conceito antes da sigla? Dá pra passar uma hora inteira ouvindo WEP, WPA2, WPS, SSL, A1, A3, token, e sair sem saber responder o que é uma chave. A sigla é o fim da história. Começar por ela é começar pelo fim.
Então vamos pelo começo. E o começo é bem mais antigo do que parece.
três mil anos embaralhando
A primeira criptografia que a gente tem registro decente não tinha matemática nenhuma. Era um bastão.
Os espartanos enrolavam uma tira de couro em volta de um bastão de espessura específica e escreviam a mensagem no sentido do comprimento. Desenrolada, a tira virava um monte de letra solta sem sentido. Pra ler, você precisava de um bastão da mesma espessura. Chamavam de cítala.
Repare no que a espessura do bastão é, nessa história: ela é a chave. Ninguém usava essa palavra, mas o papel é exatamente esse: o pedaço da informação que separa quem consegue ler de quem não consegue.
Uns seiscentos anos depois, César fazia outra coisa. Em vez de embaralhar a posição das letras, ele trocava cada letra por outra, três casas adiante no alfabeto. A vira D, B vira E, e assim até o alfabeto dar a volta.
Essas duas ideias, trocar a posição e trocar o símbolo, são a base de tudo que veio nos três mil anos seguintes. O resto foi refinamento.
E o refinamento óbvio apareceu rápido: em vez de deslocar o alfabeto por um número fixo, embaralha ele todo. Cada letra vira outra qualquer, sem padrão. Isso dá um número de arranjos possíveis com vinte e seis dígitos, o que na época parecia o fim da conversa.
Não era.
- 700 a.C.cítalaesparta enrola a tira no bastão. a espessura é a chave, e ninguém ainda tem a palavra pra isso.
- 50 a.C.cifra de Césarsubstituição por deslocamento fixo. vinte e cinco chaves possíveis, o que só é um problema depois que alguém pensa em testar todas.
- 850Al-Kindianálise de frequência em Bagdá. o primeiro método sistemático pra quebrar uma cifra sem ter a chave.
- 1553Vigenèrea cifra polialfabética que resistiu três séculos e ganhou o apelido de le chiffre indéchiffrable.
- 1863Kasiskipublica como achar o tamanho da chave do Vigenère procurando repetições. o indecifrável cai.
- 1883Kerckhoffsenuncia o princípio que separa o algoritmo da chave e vira a regra que a área segue até hoje.
Tem uma coisa em comum entre a cítala, o César e a substituição embaralhada, e é ela que explica por que tudo isso caiu: em todos os três, o segredo era o método. Quem descobrisse como a cifra funcionava lia tudo que já tinha sido escrito com ela, pra sempre.
Al-Kindi e o nascimento da criptoanálise
No século IX, em Bagdá, um sujeito chamado Al-Kindi escreveu o texto que, pra mim, é o marco real desse post inteiro.
A ideia dele é quase constrangedora de tão simples. Numa língua qualquer, as letras não aparecem com a mesma frequência. Em português, A e E são muito comuns; K e W quase não existem. Numa substituição, a letra muda de roupa, mas não muda de frequência. Se A vira Q, então Q vai aparecer no texto cifrado com a mesma abundância que A tinha no texto original.
Então você não precisa da chave. Você conta as letras.
Isso parece pouco e é enorme. É o primeiro ataque sistemático da história: um procedimento que qualquer pessoa pode seguir, que não depende de sorte nem de sacada, e que funciona contra uma família inteira de cifras em vez de uma mensagem específica.
Antes de Al-Kindi, quebrar cifra era talento. Depois dele, virou método.
Essa é a fronteira que dá nome a esse post. No instante em que existe um procedimento repetível pra atacar, existe também um critério pra avaliar defesa: dá pra dizer que uma cifra é melhor que outra, e dizer por quê. Isso é ciência. O resto era artesanato.
E foi Al-Kindi que criou o vício que a criptografia tem até hoje: ninguém acredita numa cifra porque ela parece boa. Acredita depois que gente competente tentou quebrar e não conseguiu.
Kerckhoffs: a segurança está na chave
O Vigenère foi a resposta à análise de frequência, e foi uma boa resposta. Em vez de um alfabeto de substituição, vários, alternando conforme uma palavra-chave. A mesma letra do texto claro vira letras diferentes em posições diferentes, e o perfil de frequência se achata. Ficou trezentos anos conhecido como le chiffre indéchiffrable.
Em 1863, Kasiski publicou como achar o tamanho da palavra-chave procurando trechos repetidos no texto cifrado. Achado o tamanho, o Vigenère se desmonta em vários Césares, e cada um cai na análise de frequência. Indecifrável por trezentos anos, decifrado num artigo.
Vinte anos depois, um holandês chamado Auguste Kerckhoffs escreveu a frase que organizou a área inteira.
Um sistema criptográfico deve continuar seguro mesmo que tudo sobre ele seja público, exceto a chave. Se a sua segurança depende do inimigo não saber como o seu sistema funciona, você não tem segurança. Você tem um prazo.
Isso é menos óbvio do que parece hoje. Kerckhoffs estava dizendo pra abrir mão da vantagem mais intuitiva que existe, que é o inimigo não saber o que você está fazendo. E o argumento dele é puramente prático: método vaza. Gente sai da equipe, equipamento é capturado, código é lido. A chave você troca numa tarde; o método, não.
É por isso que os algoritmos que protegem o seu banco estão publicados na internet, com especificação aberta, e isso não é um descuido. É o desenho.
E é daqui que sai a regra que fecha esse post lá no fim, a de nunca inventar a sua própria criptografia. Ela não é conservadorismo de área. É a consequência direta de Kerckhoffs: se a segurança tem que morar na chave e não no segredo do método, então o método precisa ter sido lido por muita gente. Um algoritmo que ninguém examinou não é secreto. É só desconhecido.
duas chaves, ou uma só
Criptografia simétrica é a ideia intuitiva, a que você já teve quando criança: as duas pontas combinam um segredo e usam ele pra embaralhar e desembaralhar. Uma chave só, dos dois lados.
É rápida e é isso que protege o grosso dos seus dados hoje: AES é simétrica. Mas ela tem um problema que parece bobo e é fatal: como as duas pontas combinam a chave? Se eu preciso de um canal seguro pra te mandar a chave, e a chave é justamente o que cria o canal seguro, eu ando em círculo.
Criptografia assimétrica quebra esse círculo. Em vez de uma chave, um par, ligado por matemática: o que uma fecha, só a outra abre. Uma delas você publica pro mundo inteiro. A outra nunca sai da sua máquina.
simétrica
- uma chave, os dois ladosquem cifra e quem decifra seguram exatamente o mesmo segredo.
- rápida
- e como combinar a chave?
assimétrica
- um par de chavesduas chaves ligadas por matemática: o que uma fecha, só a outra abre.
- uma delas é pública
- quebra o círculo, e é lenta
A parte que parece mágica é a de que publicar uma chave não entrega a outra. Isso se apoia em problemas matemáticos fáceis num sentido e absurdamente difíceis no sentido contrário: multiplicar dois primos gigantes é trivial, fatorar o resultado de volta não é.
Só que essa ideia é muito mais nova do que o resto do post sugere.
Diffie-Hellman e RSA
Por três mil anos, a resposta pra "como as duas pontas combinam a chave" foi sempre a mesma: alguém leva. Um mensageiro, um encontro, uma mala. A criptografia protegia a mensagem e terceirizava o problema da chave pra logística.
Isso funcionava porque os usuários eram governos e exércitos, que têm mensageiro. Quando a comunicação civil começou a crescer, deixou de funcionar. Não dá pra mandar um mensageiro pra cada par de pessoas que queira se falar, e o número de chaves necessárias cresce com o quadrado do número de participantes.
Em 1976, Whitfield Diffie e Martin Hellman publicaram um artigo mostrando que dois estranhos podem chegar num segredo compartilhado conversando em público, na frente de quem estiver ouvindo, sem nunca dizer o segredo em voz alta.
Vale parar um segundo nisso, porque soa impossível. Não é uma forma esperta de esconder a chave durante o envio. É que a chave nunca é enviada. Cada lado combina o que recebeu com algo que só ele sabe, e os dois chegam no mesmo resultado por caminhos diferentes. Quem escutou a conversa inteira tem as duas metades públicas e não consegue chegar lá.
No ano seguinte, Ron Rivest, Adi Shamir e Leonard Adleman publicaram o RSA, que dá o passo seguinte: além de acordar uma chave, dá pra ter um par permanente, com uma metade publicável. É o que finalmente separa "quem pode escrever pra mim" de "quem pode ler o que me escreveram".
Dá pra ver funcionando com números pequenos. Escolhe dois primos, e a partir deles saem as duas chaves:
- n = p·q
- 143
- φ(n) = (p−1)(q−1)
- 120
- chave pública (e, n)
- (7, 143)
- chave privada (d, n)
- (103, 143)
- cifrada m^e mod n
- 81
- decifrada c^d mod n
- 42
Duas notas de rodapé que eu acho que valem mais que a nota de rodapé.
A primeira é que o governo britânico já tinha isso. James Ellis, Clifford Cocks e Malcolm Williamson chegaram nas mesmas ideias no GCHQ alguns anos antes, e ficou classificado até 1997. Descoberto primeiro, inútil por duas décadas, porque ninguém podia usar.
A segunda é que o RSA de 1977 continua de pé em 2026. Quarenta e nove anos de gente muito boa tentando quebrar, publicamente, e o que derrubou o tamanho de chave foi o hardware ficar mais rápido, não a matemática ceder. Isso é o que "testado pelo tempo" quer dizer na prática.
assinatura digital
Tem um uso do par de chaves que quase nunca é explicado direito, e que é metade do motivo de a internet funcionar.
Até aqui, o par serviu pra esconder: você cifra com a chave pública de alguém, e só a privada daquela pessoa abre. Agora inverte a ordem. Cifra com a sua chave privada, e qualquer um consegue abrir com a sua pública.
Isso parece inútil, porque se qualquer um abre, não tem segredo nenhum. E não tem mesmo. Não é pra ter. O que isso prova é autoria: se abriu com a sua chave pública, só pode ter sido fechado com a sua privada, que só você tem.
Na prática ninguém assina a mensagem inteira, porque seria lento. Assina o hash dela, que é pequeno, de tamanho fixo, e muda inteiro se alguém encostar num byte do original. Por isso assinatura e hash andam sempre juntos, e por isso um hash quebrado quebra as assinaturas junto.
E é isso que o certificado do site faz. Ele não esconde nada. Ele é uma declaração assinada por alguém em quem o seu navegador já confia, dizendo que aquela chave pública pertence àquele domínio. Cifrar bem com o impostor errado continua sendo uma vitória inútil.
A1, A3 e token
Essa seção existe por um motivo específico: foi isso que a aula citou sem explicar, e é o tipo de coisa que soa como criptografia avançada quando não é.
A1 e A3 são tipos de certificado digital no padrão brasileiro. A diferença entre os dois não é o algoritmo, não é o tamanho da chave, não é a matemática. É onde a chave privada mora.
No A1, a chave privada é um arquivo. Você instala no computador, e ela pode ser copiada, movida, feita backup, anexada num e-mail por engano. É prático e é frágil pelo mesmo motivo.
No A3, a chave privada é gerada dentro de um token USB ou cartão e não sai de lá. Você não manda a chave pro documento; você manda o documento pro dispositivo, ele assina internamente e devolve só a assinatura. Mesmo com a máquina comprometida, o atacante consegue pedir assinaturas enquanto o token está plugado, mas não consegue levar a chave embora.
É a mesma diferença entre guardar a chave de casa no bolso e deixar ela numa fechadura que só funciona com você presente.
E o "token" da aula, que apareceu na mesma frase como se fosse um terceiro algoritmo, é isso: um pedaço de hardware. Fator de posse, não primitiva criptográfica. Pior ainda, a palavra é sobrecarregada: token de autenticação numa API é outra coisa completamente, um string assinado que o servidor emite. Mesma palavra, dois mundos, e juntar os dois numa lista de siglas é exatamente como se aprende errado.
hash não é cifra
Esse é o ponto onde mais gente se perde, e a confusão tem consequência prática.
Cifrar é uma via de mão dupla: existe uma chave que desfaz. Hash é mão única. Ele pega uma entrada de qualquer tamanho e devolve um resumo de tamanho fixo, e não existe chave que desfaça, porque não sobrou informação pra desfazer. Quando um site diz que não sabe a sua senha, é isso que ele está dizendo: ele guardou o hash, não a senha.
Um bom hash tem uma propriedade que é mais fácil ver do que explicar. Muda uma letra da entrada, uma só, e a saída inteira vira outra coisa, sem nenhuma semelhança com a anterior. Chama efeito avalanche:
mesmo texto, uma letra trocada: Criptografia
e o oposto disso, quando o hash falha: dois PDFs diferentes com o mesmo SHA-1, publicados em 2017 pelo Google e pelo CWI. valores gravados, o navegador não recalcula SHA-1 aqui.
shattered-1.pdfshattered-2.pdfIsso é o que impede alguém de chegar perto da resposta por tentativa e erro guiada: não existe "quase certo". Ou é o mesmo hash, ou não tem informação nenhuma em quanto você errou.
E é aqui que as siglas finalmente ganham sentido, porque hash é um lugar onde as coisas morrem. MD5 caiu: colisões práticas desde 2004, duas entradas diferentes com o mesmo resumo, produzidas de propósito. SHA-1 caiu em 2017, quando pesquisadores do Google e do CWI publicaram dois PDFs diferentes com o mesmo SHA-1. Os dois continuam aparecendo em sistema em produção até hoje. SHA-256 é o padrão de fato agora.
Hash de senha é um caso à parte: SHA-256 puro é rápido demais pra isso, e rapidez é justamente o que ajuda quem está tentando adivinhar. Senha pede uma função deliberadamente lenta e com sal: bcrypt, scrypt, Argon2, PBKDF2.
o cadeado do navegador
Com chave e hash na mão, o TLS deixa de ser sigla e vira uma história com começo, meio e fim. E ela responde a pergunta que ficou pendente lá em cima: se a assimétrica é lenta e a simétrica não consegue combinar a chave, como é que a internet funciona?
Funciona porque as duas trabalham juntas, em turnos.
o navegador diz quais cifras ele fala e já manda a parte pública dele do acordo de chave.
O detalhe que quase sempre some na explicação: o segredo compartilhado nunca atravessa a rede. Cada lado manda uma metade pública e calcula o mesmo resultado sozinho. Quem estiver escutando o cabo vê as duas metades e não consegue chegar no resultado.
E o certificado não tem nada a ver com embaralhar dados. Ele responde outra pergunta, que é "com quem eu estou falando afinal". Cifrar perfeitamente com o impostor errado é uma vitória inútil.
Sobre "SSL": o nome morreu. SSL 3.0 foi aposentado em 2015, e o que roda hoje é TLS, de preferência 1.3. O apelido ficou por inércia, como quem ainda chama o carro de automóvel.
o wi-fi que caiu quatro vezes
O wi-fi é o melhor estudo de caso de criptografia que existe, porque a história inteira dele é pública e se repete: alguém publica um padrão, alguém quebra, o padrão é substituído.
- 1997WEPreaproveitava o vetor de inicialização do RC4. quebrado em 2001; hoje cai em minutos.
- 2003WPAremendo de emergência (TKIP) pra rodar no hardware que já existia. sempre foi transitório.
- 2004WPA2AES de verdade. aguentou treze anos, até o KRACK em 2017 atacar a negociação, não a cifra.
- 2006WPSo botãozinho de conectar fácil. o PIN de oito dígitos podia ser adivinhado em partes, e caiu em 2011. desliga isso.
- 2018WPA3troca a negociação por um handshake que não vaza material pra ataque offline. o Dragonblood, em 2019, achou falhas de implementação, não da ideia.
Repare no padrão: o WEP morreu porque a matemática estava errada. O WPA2 e o WPA3 apanharam pela implementação e pela negociação. É a diferença mais importante desse post inteiro, e ela volta no fim.
Turing, a dobradiça
Aqui a história vira, e ela vira num ponto só.
A Enigma é a peça de criptografia mais recontada da computação, então não vou recontar o filme. Mas vale contar o mecanismo do ataque, porque é ele que importa pro resto dessa seção.
A Enigma tinha um espaço de configurações grande o bastante pra ser inviável de testar uma por uma, mesmo hoje. O que Bletchley Park explorou não foi força bruta: foi estrutura. A máquina tinha uma propriedade que parecia inofensiva: nenhuma letra podia ser cifrada nela mesma. Isso significa que, se você chuta que uma mensagem contém uma palavra provável, dá pra deslizar essa palavra ao longo do texto cifrado e descartar todas as posições onde alguma letra coincide consigo mesma.
Essas palavras prováveis eram chamadas de berços, e vinham de hábito: previsões de tempo mandadas no mesmo horário, saudações protocolares, mensagens que terminavam sempre igual. A bomba eletromecânica então testava configurações em cima do que sobrava, e cada contradição lógica eliminava um bloco inteiro de possibilidades de uma vez.
Ou seja: não se testou o espaço todo. Usou-se regularidade estatística e conhecimento prévio do conteúdo pra podar o espaço até virar algo que uma máquina da época conseguia percorrer.
Guarde esse parágrafo, porque ele vai voltar daqui a pouco com outro nome.
E aqui entra a coincidência que não é coincidência: o sujeito que liderou aquilo é o mesmo que, doze anos depois, escreveu "Computing Machinery and Intelligence", o artigo que abre com "podem as máquinas pensar" e propõe o teste que leva o nome dele.
Criptografia e inteligência artificial saíram da mesma cabeça, com uns poucos anos de distância.
E não é acaso biográfico. Releia a descrição do ataque à Enigma trocando o vocabulário: espaço de busca intratável, poda por restrição, estrutura estatística da linguagem, hipótese sobre o conteúdo provável. Isso é uma descrição de aprendizado de máquina escrita trinta anos antes de o termo existir. As duas áreas nasceram da mesma pergunta: o que uma máquina consegue inferir do que não lhe foi dito.
Depois disso elas se separaram, e ficaram setenta anos quase sem se falar.
cypherpunks, crypto wars e blockchain
Tem um pedaço dessa história que raramente entra na aula, e que é o pedaço que explica por que você tem criptografia no bolso.
Até os anos 70, criptografia forte era coisa de Estado. O que Diffie, Hellman e o RSA fizeram foi tirar isso das mãos de governos e colocar em artigo publicado, e a reação foi exatamente a que se espera.
Nos Estados Unidos, criptografia acima de certo tamanho de chave era classificada como munição para efeito de exportação. Na mesma lista de tanque e míssil. Exportar software com criptografia forte era, na letra da lei, tráfico de armas.
Em 1991, Phil Zimmermann publicou o PGP, que dava criptografia de nível militar pra qualquer pessoa com um computador. Ele virou alvo de investigação criminal federal por três anos, porque o programa saiu dos Estados Unidos pela internet. A defesa foi um golpe de gênio: o código-fonte foi publicado como livro, impresso, pelo MIT Press. Exportar armas é crime; exportar livro é liberdade de expressão, protegida pela Primeira Emenda. O caso foi arquivado em 1996.
Na mesma linha, gente andava por aí com camiseta estampada com quatro linhas de Perl que implementavam RSA, com o aviso de que aquela camiseta era, tecnicamente, uma arma de exportação controlada. Era piada e era litígio de verdade ao mesmo tempo.
Por trás disso tudo tinha uma lista de e-mail, começada em 1992, onde essa turma se organizava. Eric Hughes escreveu no manifesto do grupo a frase que resume o método: cypherpunks write code. A ideia era que discurso não protege ninguém e lei muda com eleição. O que protege é software que existe, roda e está publicado.
- 1976Diffie-Hellmandois estranhos combinam um segredo em público. a criptografia sai do monopólio estatal e entra num periódico.
- 1977RSAo par de chaves permanente. quarenta e nove anos depois, ainda de pé.
- 1991PGPZimmermann publica, e passa três anos sob investigação federal por exportação de munição.
- 1993manifesto cypherpunkcypherpunks write code. a tese de que software publicado protege mais que legislação.
- 2001AESo fim do argumento: padrão escolhido em concurso público de cinco anos, com todo mundo tentando quebrar os candidatos à vista.
- 2008Bitcoinhash, assinatura e prova de trabalho montados de outro jeito. nenhuma primitiva nova.
O Bitcoin é o que eu acho mais interessante de olhar por esse ângulo, porque ele costuma ser contado como uma ruptura tecnológica e não é. O artigo de 2008 não inventa criptografia nenhuma. Hash você já viu aqui, assinatura digital também, e prova de trabalho é de 1997, criada pra combater spam. A originalidade está inteira no arranjo, em usar essas três peças pra resolver a ordem dos eventos sem ninguém no centro.
E isso é a regra do post aparecendo de novo, por um caminho diferente. A coisa mais disruptiva que a criptografia aplicada produziu nas últimas duas décadas foi construída exclusivamente com peças velhas e auditadas. Quem inventou primitiva nova no meio de blockchain, e teve bastante gente, forneceu os exemplos do que não fazer.
A cultura hacker entra nessa história como a força que empurrou a criptografia pro público, e o instinto dela é o mesmo de Kerckhoffs: abrir o código, publicar o método, deixar o mundo inteiro tentar quebrar. Vindo de lados opostos, um professor holandês do século XIX e uma lista de e-mail anarquista dos anos 90, as duas chegam na mesma conclusão. Segredo de método é dívida. Escrutínio público é o único ativo.
os dois sacerdócios
É aqui que eu chego no que me fez escrever.
Criptografia não é um assunto dentro de segurança da informação, que por sua vez é um assunto dentro de TI. É uma ciência inteira, com sua própria matemática, suas próprias conferências, e gente que passa a carreira toda dentro de um único primitivo. Usar TLS não é saber criptografia, do mesmo jeito que chamar model.predict() não é saber machine learning.
E as duas áreas, que nasceram juntas, hoje têm culturas opostas em relação ao tempo.
A criptografia tem uma regra que todo mundo repete: não invente a sua própria. Um algoritmo novo não vale nada por ser elegante. Ele vale depois de anos de gente competente tentando quebrar e falhando em público. O AES virou padrão depois de um concurso aberto de cinco anos. A criptografia pós-quântica levou oito anos de processo público até virar norma.
A IA hoje publica o artigo em duas semanas e sobe em produção na terceira.
Não estou dizendo que uma está certa e a outra errada. Estou dizendo que as duas são fundo, não superfície, e que só uma delas está sendo tratada como se fosse superfície.
onde elas se reencontram
E, depois de setenta anos, elas voltaram a se encostar. Em três frentes.
A primeira é a mais concreta: aprendizado profundo virou ferramenta de ataque de canal lateral. Em vez de atacar a matemática do AES, você mede o consumo de energia do chip enquanto ele cifra e treina uma rede pra deduzir a chave a partir desse traço. Isso é área madura, com conjunto de dados de referência e métrica própria, e o ganho do modelo é precisar de muito menos medições do que os métodos estatísticos antigos.
A segunda é a IA virando alvo: quando você põe uma cifra dentro de uma rede neural, a rede passa a responder a entradas que a cifra nunca aceitaria, e isso abre porta. Na EUROCRYPT de 2026 saiu justamente uma criptanálise desse tipo de construção.
A terceira é o relógio quântico. O algoritmo de Shor, de 1994, mostrou que um computador quântico grande o suficiente quebra RSA e curva elíptica, ou seja, quase toda a assimétrica em uso. Ninguém tem essa máquina hoje, mas o ataque não precisa dela agora: basta gravar o tráfego cifrado de hoje e esperar. É por isso que a migração já começou.
- 1994algoritmo de Shormostra que um computador quântico suficientemente grande fatora números grandes, e derruba RSA e curva elíptica junto.
- 2016NIST abre a chamadaprocesso público pra escolher os substitutos. oito anos de análise aberta pela frente.
- 2024-08os padrões saemML-KEM (FIPS 203) pra acordo de chave, ML-DSA (FIPS 204) e SLH-DSA (FIPS 205) pra assinatura.
- 2025-03HQC como reservaum segundo mecanismo de chave, com matemática diferente, pra não apostar tudo em reticulados.
- 2030prazo reala CNSA 2.0 exige a migração dos sistemas de segurança nacional, e o NIST deprecia o nível de 112 bits.
- 2035proibidoo que ficou pra trás deixa de ser aceito.
E o aviso que falta em quase toda manchete: IA não quebra AES. Nada nas três frentes acima arranha a matemática de uma cifra moderna. O que a IA faz é atacar a implementação, o vazamento físico e a fronteira entre modelo e cifra. É exatamente a mesma lição do WPA2.
o que eu já quebrei
Eu ia ficar mal-acostumado de escrever tudo isso sem dizer onde eu mesmo errei. Todos os quatro são de código meu, em produção, e todos foram consertados.
O primeiro é o meu favorito porque é quase poético. Eu tinha uma constante declarada com validade de quinze minutos pro token de acesso, bonitinha, no topo do arquivo. E ela nunca era passada pra função que assinava o token. O resultado é que os tokens saíam sem campo de expiração nenhum, ou seja, não expiravam nunca. O código dizia quinze minutos. O sistema entregava eternidade. Hoje ele rejeita qualquer token que chegue sem prazo, em vez de confiar que o prazo foi posto.
O segundo não é criptografia, é o que fica em volta dela, e é pior. Eu tinha uma função que checava papel de usuário antes de liberar rota de administrador. Ela estava registrada com o escopo errado do framework, uma palavra, e por causa disso não valia fora do arquivo onde foi declarada. Nove checagens de permissão viraram enfeite. Qualquer usuário autenticado alcançava rota de admin. O código parecia certo, revisava bem, e não fazia absolutamente nada.
O terceiro é o oposto: deu certo. Eu tinha um endpoint de download de arquivo que era público e montava o caminho concatenando o que vinha na URL, sem autenticação, sem assinatura, e sem conferir se o caminho continuava dentro da pasta. Quem adivinhasse um nome baixava o arquivo, e uma sequência de ../ saía da pasta inteira. A troca foi por URL assinada com HMAC sobre a chave e o prazo, comparação em tempo constante, e o caminho resolvido e conferido contra a raiz. Um detalhe que eu só entendi escrevendo: a assinatura é conferida antes da expiração, de propósito. Se eu checasse a validade primeiro, a diferença entre "assinatura inválida" e "link expirado" contaria pra quem estivesse sondando que aquela assinatura era boa.
O quarto é o mesmo HMAC com outro modelo de ameaça: webhook de pagamento. O provedor assina cada notificação, e o meu lado recalcula a assinatura, compara em tempo constante e rejeita qualquer coisa fora de uma janela de cinco minutos, pra ninguém reenviar uma notificação legítima capturada antes. E a regra que vale mais que a criptografia toda: o corpo do webhook nunca decide nada. Ele é um aviso pra eu ir perguntar o status na API do provedor, que é a única fonte de verdade.
Esses quatro têm a mesma moral, e é a moral do WPA2: a matemática não falhou em nenhum deles. Falhou o que estava em volta: uma constante que não chegou ao destino, uma palavra de escopo, um caminho não validado, uma ordem de checagem. É sempre a costura.
o que eu levei da aula ruim
Que criptografia é uma ciência à parte, e que isso não é desculpa pra não entender o básico. É motivo pra respeitar o básico.
Eu não vou virar criptógrafo. Ninguém precisa virar. Mas saber o que é uma chave, por que hash não volta, e onde a assimétrica passa o bastão pra simétrica é a diferença entre usar a ferramenta e ser usado por ela. E saber que existe uma ciência inteira atrás dela é o que te impede de inventar a sua própria, que é, no fim, a única regra que a criptografia realmente pede de quem está de fora.