Study guide

Cryptography and keys: public, private, sessions and SSH.

How encryption, signatures and key pairs work, how apps keep a private key on the device, how the session carries on from there, and what SSH does step by step.

Resumo (TL;DR)Summary (TL;DR)

Onde esta nota se encaixa: é o alicerce de matemática e chaves por baixo de login, HTTPS e SSH. O mapa de identidade (SSO, OAuth, OIDC) está em Login e autenticação; sessões e cookies do lado do app, em Apps web seguros; o uso prático com chaves de curta duração, em GitHub para AWS com OIDC.Where this note fits: it is the math-and-keys foundation under sign-in, HTTPS and SSH. The identity map (SSO, OAuth, OIDC) is in Sign-in and authentication; sessions and cookies from the app’s side, in Secure web apps; the practical use with short-lived credentials, in GitHub to AWS with OIDC.
  1. Chave simétrica: um segredo só, igual nos dois lados (rápido, mas difícil de combinar). Par de chaves: uma pública (todos podem ter) e uma privada (só você). O que uma fecha, só a outra abre.Symmetric key: a single secret, the same on both sides (fast, but hard to agree on). Key pair: a public key (everyone may have it) and a private key (only you). What one locks, only the other unlocks.
  2. Com o par você cifra (pública cifra, privada decifra) e assina (privada assina, pública verifica). Na prática, tudo combina os dois mundos: o par acorda uma chave simétrica e a simétrica protege os dados (TLS, SSH).With the pair you encrypt (public encrypts, private decrypts) and sign (private signs, public verifies). In practice everything mixes both worlds: the pair agrees on a symmetric key and the symmetric key protects the data (TLS, SSH).
  3. Apps com a chave privada no aparelho (passkeys, bancos, autenticadores) provam quem você é assinando um desafio; o servidor só guarda a pública. Depois da prova, uma sessão (cookie ou token) evita repetir a assinatura a cada requisição. O SSH usa o mesmo truque: o servidor se prova a você, depois você se prova a ele.Apps with the private key on the device (passkeys, banks, authenticators) prove who you are by signing a challenge; the server only keeps the public key. After the proof, a session (cookie or token) avoids repeating the signature on every request. SSH uses the same trick: the server proves itself to you, then you prove yourself to it.

Três promessas e um ingredienteThree promises and one ingredient

Criptografia não é uma coisa só: é um conjunto de ferramentas que entregam promessas diferentes. Saber qual promessa você quer evita usar a ferramenta errada.Cryptography is not one thing: it is a toolbox whose tools deliver different promises. Knowing which promise you want avoids using the wrong tool.

PromessaPromiseSignificaMeansFerramentaTool
Sigilo (confidencialidade)Secrecy (confidentiality)Só quem deve consegue ler.Only the intended people can read it.Cifra (simétrica ou assimétrica)Cipher (symmetric or asymmetric)
IntegridadeIntegrityNinguém alterou o dado no caminho.Nobody changed the data on the way.Hash, MAC, assinaturaHash, MAC, signature
AutenticidadeAuthenticityVeio mesmo de quem diz que enviou.It really came from who says sent it.Assinatura digital, certificadoDigital signature, certificate

O ingrediente: o hashThe ingredient: the hash

Um hash transforma qualquer dado em um resumo de tamanho fixo. Mesma entrada, mesmo resumo; mudou um caractere, o resumo muda por inteiro; e não há caminho de volta. Ele não esconde nada (não é cifra): serve de impressão digital, e por isso aparece dentro das assinaturas, dos certificados e das senhas guardadas.A hash turns any data into a fixed-size digest. Same input, same digest; change one character and the whole digest changes; and there is no way back. It hides nothing (it is not a cipher): it works as a fingerprint, which is why it shows up inside signatures, certificates and stored passwords.

Olá, mundo SHA-256SHA-256 b8a0136dcb2459c3070d390239f18258248d9f9d… Olá, mundo! SHA-256SHA-256 9583b013baa520d3a893c4270d0c67732d7ef176… ↑ muda 1 caractere → o resultado inteiro muda↑ change 1 character → the whole result changes Mesma entrada → mesmo hashSame input → same hash Entrada de qualquer tamanho → saída de tamanho fixo (256 bits)Input of any size → fixed-size output (256 bits) Mão única: do hash não se volta ao texto. É uma impressão digital, não uma cifra.One way: you cannot go from hash back to text. It is a fingerprint, not a cipher.
Hash é a impressão digital de um dado. Os valores acima são SHA-256 reais (truncados na tela).A hash is the fingerprint of a piece of data. The values above are real SHA-256 digests (truncated on screen).
Três palavras que não são sinônimos. Cifrar esconde com uma chave e dá para desfazer; hash resume e não dá para desfazer; codificar (Base64, URL-encoding) só muda a representação e não protege nada. Um JWT, por exemplo, é Base64URL: qualquer um lê; o que o protege é a assinatura.Three words that are not synonyms. Encrypting hides with a key and can be undone; hashing summarizes and cannot be undone; encoding (Base64, URL-encoding) only changes the representation and protects nothing. A JWT, for example, is Base64URL: anyone can read it; what protects it is the signature.

Chave simétrica: um segredo, dois ladosSymmetric key: one secret, two sides

É a ideia mais antiga: a mesma chave cifra e decifra. Pense em um cofre com uma só chave, da qual existem duas cópias.It is the oldest idea: the same key encrypts and decrypts. Think of a safe with a single key, of which there are two copies.

AliceAlice BobBob textotext "oi""hi" cifrarencrypt AES cifradociphertext x9#kQ2… decifrardecrypt AES textotext "oi""hi" a MESMA chave nos dois ladosthe SAME key on both sides (precisa ser combinada antes, em segredo)(must be agreed beforehand, in secret) Rápido e simples, mas: como entregar a chave sem ninguém copiar?Fast and simple, but: how do you hand over the key without anyone copying it? Para n pessoas conversarem em pares são n(n−1)/2 chaves: 10 pessoas → 45 · 100 pessoas → 4.950.For n people to talk in pairs you need n(n−1)/2 keys: 10 people → 45 · 100 people → 4,950.
Na simétrica há um só segredo compartilhado. O problema deixa de ser a matemática e passa a ser a distribuição da chave.Symmetric encryption has a single shared secret. The problem stops being the math and becomes distributing the key.
AlgoritmoAlgorithmPara que serveWhat it is forNotaNote
AES (128/256 bits)Padrão de fato para cifrar dados: arquivos, discos, TLS.The de facto standard for encrypting data: files, disks, TLS.Usado em modos autenticados como GCM, que também detectam alteração.Used in authenticated modes such as GCM, which also detect tampering.
ChaCha20-Poly1305Alternativa moderna ao AES, rápida mesmo sem hardware dedicado (celulares).Modern alternative to AES, fast even without dedicated hardware (phones).Presente no TLS 1.3 e no SSH.Present in TLS 1.3 and SSH.
HMAC (ex.: HMAC-SHA-256)Não cifra: prova integridade e autoria entre quem divide o segredo.Does not encrypt: proves integrity and origin between parties that share the secret.É como as requisições da AWS (SigV4) são assinadas com a secret key.It is how AWS requests (SigV4) are signed with the secret key.
O limite da simétrica não é a segurança, é a logística. Para duas pessoas que nunca se encontraram, como combinar a chave sem que alguém a copie no caminho? E com muitas pessoas, o número de chaves explode. A criptografia assimétrica existe para resolver isso.The limit of symmetric is not security, it is logistics. For two people who never met, how do you agree on the key without someone copying it on the way? And with many people, the number of keys explodes. Asymmetric cryptography exists to solve this.

Chaves pública e privadaPublic and private keys

Aqui a chave vem em par, gerado junto por uma conta matemática: o que uma chave faz, só a outra desfaz. Uma você espalha (pública); a outra nunca sai de você (privada). Descobrir a privada a partir da pública é inviável com os tamanhos usados hoje.Here the key comes as a pair, generated together by a mathematical operation: what one key does, only the other undoes. You spread one (public); the other never leaves you (private). Deriving the private key from the public one is infeasible at today’s key sizes.

Analogia do cadeado. Você fabrica milhares de cadeados abertos idênticos e os distribui (chave pública). Qualquer um pode fechar um cadeado numa caixa e mandar para você. Só você tem a chave que abre (chave privada). Quem distribuiu cadeados não perdeu segurança alguma.Padlock analogy. You make thousands of identical open padlocks and hand them out (public key). Anyone can snap one shut on a box and send it to you. Only you have the key that opens it (private key). Handing out padlocks cost you no security at all.
BobBob privada: só Bobprivate: Bob only pública: para todospublic: for everyone AliceAlice quer enviar "oi"wants to send "hi" cópia da públicacopy of the public one 1 envia a chave públicasends the public key (por qualquer canal, até público)(over any channel, even public) x9#kQ2… 2 cifra com a pública de Bobencrypts with Bob’s public key 3 só a privada de Bob decifraonly Bob’s private key decrypts Quem intercepta o canal (Eve) vê só x9#kQ2…: a pública não decifra o que ela mesma cifrou.Whoever taps the channel (Eve) sees only x9#kQ2…: the public key cannot decrypt what it encrypted.
Pense num cadeado aberto: Bob distribui cópias à vontade, qualquer um fecha, mas só ele tem a chave que abre.Think of an open padlock: Bob hands out copies freely, anyone can snap one shut, but only he holds the key that opens it.

Dois usos opostos do mesmo parTwo opposite uses of the same pair

Cifrar → sigiloEncrypt → secrecy Assinar → autenticidadeSign → authenticity RemetenteSender DestinatárioRecipient texto cifradociphertext pública dorecipient’s destinatáriopublic key privada dorecipient’s destinatárioprivate key Qualquer um cifra;Anyone can encrypt; só o dono da privada lê.only the private-key owner reads. AutorAuthor VerificadorVerifier mensagemmessage + assinatura+ signature privadaauthor’s do autorprivate key públicaauthor’s do autorpublic key Qualquer um verifica;Anyone can verify; só o dono da privada assina.only the private-key owner signs.
O mesmo par serve a duas coisas opostas: a pública protege o que vai para o dono; a privada prova que algo veio do dono.The same pair does two opposite jobs: the public key protects what goes to the owner; the private key proves something came from the owner.
CifrarEncryptAssinarSign
Quem usa a privadaWho uses the private keyDestinatário, para lerRecipient, to readAutor, para assinarAuthor, to sign
Quem usa a públicaWho uses the public keyQualquer um, para cifrarAnyone, to encryptQualquer um, para verificarAnyone, to verify
GaranteGuaranteesSigiloSecrecyAutenticidade e integridadeAuthenticity and integrity
Cuidado com o ditado “assinar é cifrar com a privada”. É uma simplificação que funciona no RSA clássico, mas assinatura e cifragem são operações diferentes (e algoritmos como Ed25519 só assinam). Pense em dois papéis: a privada prova autoria; a pública protege o envio ao dono.Beware of the saying “signing is encrypting with the private key”. It is a simplification that works for classic RSA, but signing and encrypting are different operations (and algorithms like Ed25519 only sign). Think of two roles: the private key proves authorship; the public key protects what is sent to the owner.

Algoritmos que você encontraAlgorithms you will meet

AlgoritmoAlgorithmFazDoesOnde apareceWhere you see itNotaNote
RSACifrar e assinarEncrypt and signCertificados mais antigos, chaves SSH antigas, JWT RS256Older certificates, older SSH keys, JWT RS256Chaves grandes (2048 bits no mínimo; 3072 ou 4096 para folga). Mais lento e mais pesado.Large keys (2048 bits at least; 3072 or 4096 for margin). Slower and heavier.
ECDSA (curvas P-256, P-384)AssinarSignCertificados TLS, JWT ES256, passkeysTLS certificates, JWT ES256, passkeysChaves curtas para a mesma força que o RSA.Short keys for the same strength as RSA.
Ed25519AssinarSignChaves SSH modernas, assinatura de commitsModern SSH keys, commit signingRápido, chaves pequenas e poucas armadilhas de uso. Padrão recomendado para novas chaves SSH.Fast, small keys and few pitfalls. The recommended default for new SSH keys.
X25519 / ECDHAcordar uma chave compartilhadaAgree on a shared keyTLS 1.3, SSHTLS 1.3, SSHNão cifra nem assina: só produz o segredo comum (veja a seção de TLS).Neither encrypts nor signs: it only produces the common secret (see the TLS section).

Assinatura digital passo a passoDigital signature step by step

A assinatura responde duas perguntas ao mesmo tempo: quem fez isto e se algo mudou desde então. Ela não esconde o conteúdo; qualquer um lê, e qualquer um confere.A signature answers two questions at once: who made this and whether anything changed since. It does not hide the content; anyone can read it, and anyone can check it.

ASSINAR (o autor, com a chave privada)SIGN (the author, with the private key) documentodocument hashhash SHA-256 resumodigest H assina com asigns with the chave PRIVADAPRIVATE key assinaturasignature S VERIFICAR (qualquer um, com a chave pública)VERIFY (anyone, with the public key) documentodocument recebidoreceived hashhash SHA-256 resumodigest H₁ assinaturasignature S abre com aopens with the chave PÚBLICAPUBLIC key resumodigest H₂ =?=? iguais: válidoequal: valid autor certo, texto intactoright author, text intact Se 1 bit do documento mudar, H₁ ≠ H₂ e a verificação falha. Sem a privada, ninguém gera uma S válida.If a single bit of the document changes, H₁ ≠ H₂ and verification fails. Without the private key, nobody can produce a valid S.
Na prática assina-se o hash do documento (curto e de tamanho fixo), não o documento inteiro. Detalhes variam por algoritmo; a ideia é esta.In practice you sign the hash of the document (short, fixed-size), not the whole document. Details vary by algorithm; the idea is this.
  • Em um JWT: o emissor assina cabeçalho + payload com a chave privada (RS256, ES256); quem recebe baixa as chaves públicas do emissor (o endereço jwks_uri do documento de descoberta do OIDC) e verifica. Foi assim que a AWS confiou no token do GitHub Actions.In a JWT: the issuer signs header + payload with the private key (RS256, ES256); the receiver downloads the issuer’s public keys (the jwks_uri address in the OIDC discovery document) and verifies. That is how AWS trusted the GitHub Actions token.
  • Em um commit do Git: você assina com a privada; o GitHub mostra “Verified” ao conferir com a pública cadastrada na sua conta.In a Git commit: you sign with the private key; GitHub shows “Verified” after checking against the public key registered on your account.
  • Em um certificado TLS: a autoridade certificadora assina “esta chave pública pertence a este domínio”.In a TLS certificate: the certificate authority signs “this public key belongs to this domain”.
HS256 é outra coisa. No JWT HS256 existe um segredo compartilhado (HMAC): quem verifica também consegue forjar. Com RS256/ES256, só o dono da privada assina. Sempre fixe o algoritmo esperado ao verificar (RFC 8725).HS256 is something else. In an HS256 JWT there is a shared secret (HMAC): whoever verifies can also forge. With RS256/ES256, only the private-key owner signs. Always pin the expected algorithm when verifying (RFC 8725).

Juntando tudo: troca de chaves, TLS e certificadosPutting it together: key exchange, TLS and certificates

A assimétrica é mais lenta e só trata blocos pequenos; a simétrica é rápida e cuida de qualquer volume, mas precisa de uma chave combinada. A solução é híbrida: use a assimétrica para combinar uma chave e a simétrica para proteger os dados. É assim no HTTPS e no SSH.Asymmetric is slower and handles only small blocks; symmetric is fast and handles any volume, but needs an agreed key. The solution is hybrid: use asymmetric to agree on a key and symmetric to protect the data. That is how HTTPS and SSH work.

Acordar uma chave em público: Diffie-HellmanAgreeing on a key in public: Diffie-Hellman

Duas partes trocam mensagens à vista de todos e, no fim, cada uma calcula o mesmo segredo sem que ele tenha trafegado. A analogia das tintas mostra a intuição: misturar é fácil, desmisturar é inviável.Two parties exchange messages in plain sight and, at the end, each computes the same secret without it ever having travelled. The paint analogy shows the intuition: mixing is easy, unmixing is infeasible.

AliceAlice BobBob cor pública (todos veem)public color (everyone sees) segredo de AliceAlice’s secret segredo de BobBob’s secret canal público: Eve vê tudo o que passa aquipublic channel: Eve sees everything that passes here amarelo + vermelho = laranjayellow + red = orange amarelo + azul = verdeyellow + blue = green verde + vermelhogreen + red laranja + azulorange + blue mesmo marrom nos dois ladossame brown on both sides = segredo compartilhado= shared secret Eve tem amarelo, laranja e verde,Eve has yellow, orange and green, mas não consegue "desmisturar" para achar o vermelho ou o azul.but cannot "unmix" to recover the red or the blue.
Misturar é fácil, desmisturar é inviável. Na prática a "tinta" é matemática (curvas elípticas, como no X25519), e o resultado vira a chave simétrica da sessão.Mixing is easy, unmixing is infeasible. In practice the "paint" is math (elliptic curves, as in X25519), and the result becomes the session’s symmetric key.
Chaves efêmeras e sigilo futuro. No TLS 1.3 e no SSH as chaves desse acordo são geradas para a conexão e descartadas depois (forward secrecy). Se alguém roubar a chave privada do servidor no futuro, as conversas antigas gravadas continuam ilegíveis.Ephemeral keys and forward secrecy. In TLS 1.3 and SSH the keys for this agreement are generated for the connection and discarded afterwards. If someone steals the server’s private key in the future, old recorded conversations stay unreadable.

O handshake do TLS 1.3The TLS 1.3 handshake

NavegadorBrowser ServidorServer Handshake: criptografia assimétricaHandshake: asymmetric cryptography Dados: criptografia simétrica (rápida)Data: symmetric cryptography (fast) ① ClientHello① ClientHello algoritmos aceitos + metade pública efêmera (X25519)accepted algorithms + ephemeral public half (X25519) ② ServerHello② ServerHello algoritmo escolhido + metade pública do servidorchosen algorithm + the server’s public half os dois calculam o mesmo segredo e derivam as chaves de sessãoboth compute the same secret and derive the session keys ③ Certificado + assinatura③ Certificate + signature (já cifrado) prova que o servidor é dono do domínio(already encrypted) proves the server owns the domain ④ Dados HTTP cifrados④ Encrypted HTTP data AES-GCM ou ChaCha20-Poly1305, com a chave de sessãoAES-GCM or ChaCha20-Poly1305, with the session key ← resposta cifrada com a mesma chave de sessão← response encrypted with the same session key
Sequência simplificada do TLS 1.3. A criptografia assimétrica só faz o acordo de chave e a prova de identidade; os dados passam pela simétrica.Simplified TLS 1.3 sequence. Asymmetric cryptography only does the key agreement and identity proof; the data goes through symmetric encryption.

Certificados: quem garante que a chave pública é do site?Certificates: who guarantees the public key belongs to the site?

Se o seu navegador aceitasse qualquer chave pública enviada pelo servidor, um intermediário poderia mandar a dele. O certificado resolve: é a chave pública do site mais o nome do domínio, assinada por uma autoridade (CA) em quem o sistema já confia. As raízes confiáveis vêm instaladas no sistema operacional e no navegador.If your browser accepted any public key the server sent, a man in the middle could send its own. The certificate fixes this: it is the site’s public key plus the domain name, signed by an authority (CA) the system already trusts. The trusted roots ship with the operating system and the browser.

Autoridade raiz (Root CA)Root CA já vem instalada no sistema/navegadorships with the OS/browser Autoridade intermediáriaIntermediate CA assinada pela raizsigned by the root Certificado do site: baselarte.comSite certificate: baselarte.com assinado pela intermediária · traz a chave públicasigned by the intermediate · carries the public key assinasigns assinasigns O navegador confere:The browser checks: 1 cada assinatura da cadeia,each signature in the chain, até uma raiz confiávelup to a trusted root 2 o nome no certificado =the name in the certificate = o domínio acessadothe domain visited 3 a data: dentro da validadethe date: within the validity period 4 depois: o servidor assina o handshakethen: the server signs the handshake com a privada do certificadowith the certificate’s private key
Um certificado é uma chave pública com um nome, assinada por alguém em quem o navegador já confia. A confiança desce a cadeia.A certificate is a public key with a name, signed by someone the browser already trusts. Trust flows down the chain.
O cadeado do navegador prova o canal, não a honestidade. Ele diz que você fala com quem controla o domínio e que ninguém lê no meio. Um site de golpe também pode ter um certificado válido para o domínio dele.The browser padlock proves the channel, not honesty. It says you are talking to whoever controls the domain and that nobody reads in the middle. A scam site can also hold a valid certificate for its own domain.

Apps com a chave privada no aparelhoApps with the private key on the device

Passkeys, apps de banco, autenticadores e chaves de segurança seguem o mesmo desenho: o aparelho gera o par, guarda a privada e entrega ao servidor só a pública. Daí em diante, entrar é assinar um desafio, não digitar um segredo que o servidor também conhece.Passkeys, banking apps, authenticators and security keys follow the same design: the device generates the pair, keeps the private key and gives the server only the public key. From then on, signing in is signing a challenge, not typing a secret the server also knows.

1. Cadastro: o par nasce no aparelho1. Enrollment: the pair is born on the device

Seu aparelhoYour device appapp chip segurosecure chip Enclave · TPM · StrongBoxEnclave · TPM · StrongBox privada: nasce e fica aquiprivate: born and stays here pública: pode sairpublic: may leave a privada é marcada como "não exportável"the private key is marked "non-exportable" ServidorServer tabela de contasaccounts table gustavogustavo credencial: idcredential: id chave pública: …public key: … guarda só a públicastores only the public key vazar o banco não permiteleaking the database does not let entrar como vocêanyone sign in as you só a pública viajapublic key only
No cadastro (registro de passkey, ativação de biometria num app), o aparelho gera o par; a privada fica no chip, a pública vai para o servidor.At enrollment (registering a passkey, enabling biometrics in an app), the device generates the pair; the private key stays in the chip, the public key goes to the server.

2. Login: o servidor desafia, o aparelho assina2. Sign-in: the server challenges, the device signs

Aparelho + appDevice + app ServidorServer ① quero entrar como "gustavo"① I want to sign in as "gustavo" ② desafio: número aleatório novo (nonce)② challenge: a fresh random number (nonce) ③ biometria ou PIN③ biometrics or PIN libera o uso da chave (local)unlocks the key (local only) ④ o chip assina o desafio④ the chip signs the challenge com a chave privadawith the private key ⑤ assinatura do desafio (+ domínio/app)⑤ signature of the challenge (+ domain/app) ⑥ verifica com a chave pública⑥ verifies with the public key guardada no cadastro → okstored at enrollment → ok
O servidor nunca recebe senha nem a chave privada: recebe a prova de que o aparelho a possui. Como o desafio é novo a cada vez, copiar a resposta não adianta.The server never receives a password or the private key: it receives proof the device holds it. Since the challenge is new each time, copying the answer is useless.
  • Por que um desafio novo a cada vez? Se a assinatura fosse sempre a mesma, quem a interceptasse poderia reenviá-la (ataque de replay). Com um número aleatório inédito, cada resposta só vale uma vez.Why a new challenge every time? If the signature were always the same, whoever intercepted it could resend it (replay attack). With a never-seen random number, each answer is good only once.
  • Por que a biometria não vai para o servidor? Ela só autoriza o chip a usar a chave, localmente. O servidor recebe uma assinatura, nunca a digital nem o rosto.Why does the biometric not go to the server? It only authorizes the chip to use the key, locally. The server receives a signature, never the fingerprint or the face.
  • Por que resiste a phishing? No WebAuthn a assinatura cobre o domínio (origem) da página. Uma página falsa em outro domínio não consegue obter uma assinatura que valha para o site verdadeiro.Why is it phishing-resistant? In WebAuthn the signature covers the page’s domain (origin). A fake page on another domain cannot obtain a signature that is valid for the real site.
  • E se vazar o banco de dados do servidor? Lá só há chaves públicas, que não permitem assinar. Compare com senhas, em que o vazamento de hashes já ajuda quem ataca.And if the server database leaks? It only holds public keys, which cannot sign. Compare with passwords, where leaked hashes already help the attacker.

Onde fica a chave privadaWhere the private key lives

App (código do aplicativo)App (application code) só pede: "assine isto"only asks: "sign this" API do sistema (Keychain, Keystore, CNG)OS API (Keychain, Keystore, CNG) controla quem pode usar a chavecontrols who may use the key Hardware seguro (Enclave, TEE/StrongBox, TPM)Secure hardware (Enclave, TEE/StrongBox, TPM) a chave privada vive e assina aqui dentrothe private key lives and signs in here ↓ pedido de assinatura↓ signing request ↑ só a assinatura volta↑ only the signature comes back A chave privada nunca sobeThe private key never moves up ao app nem à memória comumto the app or to ordinary memory Limite honesto: aparelho comprometidoHonest limit: a compromised device e desbloqueado ainda pode PEDIRthat is unlocked can still ASK for assinaturas, mas não COPIA a chave.signatures, but cannot COPY the key.
Em cada plataforma o nome muda, a ideia não: um cofre em hardware que assina por você e nunca entrega a chave.Names change per platform, the idea does not: a hardware vault that signs for you and never hands over the key.
PlataformaPlatformCofreVaultComportamentoBehavior
iPhone / MacSecure Enclave + KeychainSecure Enclave + KeychainChaves podem ser geradas dentro do Enclave e não saem dele; o app só pede a assinatura.Keys can be generated inside the Enclave and never leave it; the app only requests the signature.
AndroidAndroid Keystore (TEE ou StrongBox)Android Keystore (TEE or StrongBox)Chaves protegidas por hardware, marcadas como não exportáveis; uso pode exigir biometria.Hardware-backed keys, marked non-exportable; use can require biometrics.
Windows / LinuxTPMTPMChip na placa-mãe que guarda e usa chaves sem entregá-las.Chip on the motherboard that stores and uses keys without handing them out.
Chave de segurançaYubiKey e similares (FIDO2)YubiKey and similar (FIDO2)Hardware dedicado: a chave nunca está no seu computador e vale em vários aparelhos.Dedicated hardware: the key is never on your computer and works across devices.
Gerenciador de senhasCofre sincronizadoSynced vaultPasskeys sincronizadas entre aparelhos: mais conveniência, e a segurança passa a depender da conta do gerenciador.Passkeys synced across devices: more convenience, and security now depends on the manager’s account.
Perdeu o aparelho? A chave privada some com ele, e é isso que se quer. O servidor precisa de um caminho de recuperação (outra passkey, códigos de backup) e de um modo de revogar a chave pública antiga. Planejar a recuperação faz parte do projeto, não é detalhe.Lost the device? The private key goes with it, which is what you want. The server needs a recovery path (another passkey, backup codes) and a way to revoke the old public key. Planning recovery is part of the design, not a detail.

E depois do login: a sessãoAfter sign-in: the session

Assinar um desafio a cada clique seria inviável (e irritante: uma biometria por requisição). Por isso a prova por chave serve para abrir uma sessão, e a sessão vale por um tempo.Signing a challenge on every click would be impractical (and annoying: one biometric prompt per request). So the key proof is used to open a session, and the session lasts for a while.

App / navegadorApp / browser ServidorServer ① login por chave (desafio + assinatura): acontece UMA vez① key login (challenge + signature): happens ONCE a chave privada é usada só neste passothe private key is used only in this step ② cria a sessão no servidor② creates the session on the server sid=7f3a… → gustavo · 8hsid=7f3a… → gustavo · 8h ③ Set-Cookie: sid=7f3a… (HttpOnly; Secure; SameSite)③ Set-Cookie: sid=7f3a… (HttpOnly; Secure; SameSite) ④ GET /conta + Cookie: sid=7f3a…④ GET /account + Cookie: sid=7f3a… 200 OK: o servidor achou o sid e sabe que é o gustavo200 OK: the server found the sid and knows it is gustavo ⑤ ação sensível → pode exigir nova assinatura (step-up)⑤ sensitive action → may require a new signature (step-up) ⑥ logout ou expiração: servidor apaga o sid; o cookie vira inútil⑥ logout or expiry: the server deletes the sid; the cookie becomes useless
A prova por chave abre a sessão; as requisições seguintes mostram apenas o cookie (ou token). Quem roubar o cookie age como você até a sessão cair.The key proof opens the session; later requests show only the cookie (or token). Whoever steals the cookie acts as you until the session ends.
Sessão com ID opaco (cookie)Opaque session ID (cookie)Tokens (access + refresh, JWT)Tokens (access + refresh, JWT)
O que o cliente guardaWhat the client holdsUm ID aleatório sem significado.A random ID with no meaning.Um token assinado com claims dentro.A signed token with claims inside.
Onde está o estadoWhere the state livesNo servidor (memória, Redis, banco).On the server (memory, Redis, database).No próprio token; o servidor só verifica a assinatura.In the token itself; the server only verifies the signature.
Encerrar à forçaForce-ending itFácil: apaga o ID no servidor.Easy: delete the ID on the server.Mais difícil: o token vale até expirar; por isso o access token é curto e há refresh token.Harder: the token is valid until it expires; hence a short access token and a refresh token.
CuidadosCare pointsHttpOnly, Secure, SameSite; renovar o ID após o login.HttpOnly, Secure, SameSite; renew the ID after login.Fixar o algoritmo, validar iss, aud, exp; guardar o refresh com mais cuidado.Pin the algorithm, validate iss, aud, exp; guard the refresh token more carefully.
A sessão é um “portador”: quem tiver o cookie ou o token age como você. A chave no hardware protege o login, mas não impede que um token roubado seja usado até expirar. Por isso: prazos curtos, revogação, reautenticação em ações sensíveis (step-up) e, em cenários avançados, tokens amarrados a uma chave do cliente (DPoP, RFC 9449).The session is a “bearer”: whoever holds the cookie or token acts as you. The hardware key protects the sign-in, but does not stop a stolen token from being used until it expires. Hence: short lifetimes, revocation, re-authentication on sensitive actions (step-up) and, in advanced setups, tokens bound to a client key (DPoP, RFC 9449).

Como as sessões, o OAuth e o OIDC se encaixam nisso está em Login e autenticação, e os detalhes de cookies e JWT do lado de quem constrói o app estão em Apps web seguros.How sessions, OAuth and OIDC fit in is covered in Sign-in and authentication, and the cookie and JWT details from the app builder’s side are in Secure web apps.

Como o SSH funcionaHow SSH works

SSH (Secure Shell) abre um canal cifrado até outra máquina para shell remoto, execução de comandos, transferência de arquivos (scp, sftp) e túneis. É a seção anterior aplicada: acordo de chave efêmera, assinaturas, chaves públicas e privadas, e um túnel simétrico.SSH (Secure Shell) opens an encrypted channel to another machine for a remote shell, running commands, file transfer (scp, sftp) and tunnels. It is the previous sections applied: ephemeral key agreement, signatures, public and private keys, and a symmetric tunnel.

As três camadasThe three layers

Camada de conexãoConnection layer canais: shell, comando, sftp, túneis de portachannels: shell, command, sftp, port tunnels RFC 4254 Camada de autenticação do usuárioUser authentication layer senha, chave pública, etc.password, public key, etc. RFC 4252 Camada de transporteTransport layer troca de chaves · cifra · integridade · autentica o SERVIDORkey exchange · encryption · integrity · authenticates the SERVER RFC 4253 TCP, porta 22TCP, port 22 o transporte de rede comumthe ordinary network transport
O SSH constrói primeiro um túnel seguro que prova quem é o servidor; só depois, dentro dele, prova quem é você.SSH first builds a secure tunnel that proves who the server is; only then, inside it, does it prove who you are.

Quem confia em quem: os arquivosWho trusts whom: the files

O SSH tem duas verificações, uma em cada sentido, e cada uma usa um arquivo diferente. Confundi-las é a origem da maioria dos erros.SSH has two checks, one in each direction, and each uses a different file. Mixing them up is the source of most errors.

Seu computador (cliente)Your computer (client) ServidorServer ~/.ssh/id_ed25519 privada · chmod 600 · nunca saiprivate · chmod 600 · never leaves ~/.ssh/id_ed25519.pub pública · pode ser copiadapublic · safe to copy ~/.ssh/known_hosts impressões dos servidores em quefingerprints of servers you você confia: você verifica o SERVIDORtrust: you verify the SERVER ssh_host_ed25519_key privada do servidor (host key)server’s private host key ssh_host_ed25519_key.pub pública do servidorserver’s public host key ~/.ssh/authorized_keys chaves públicas de quem podepublic keys of who may entrar como este usuário:log in as this user: o servidor verifica VOCÊthe server verifies YOU 1 2 1 você copia a pública para o servidor (ssh-copy-id)you copy the public key to the server (ssh-copy-id) 2 na 1ª conexão você aceita a impressão do servidoron the 1st connection you accept the server’s fingerprint
Dois sentidos de confiança: known_hosts (você confere o servidor) e authorized_keys (o servidor confere você). Cada lado guarda a PÚBLICA do outro.Two directions of trust: known_hosts (you check the server) and authorized_keys (the server checks you). Each side keeps the other’s PUBLIC key.
PerguntaQuestionQuem verificaWho checksArquivoFileSe falharIf it fails
“Este servidor é mesmo o servidor?”“Is this server really the server?”Você (cliente)You (client)~/.ssh/known_hosts~/.ssh/known_hostsAviso “REMOTE HOST IDENTIFICATION HAS CHANGED”“REMOTE HOST IDENTIFICATION HAS CHANGED” warning
“Esta pessoa pode entrar?”“May this person log in?”ServidorServer~/.ssh/authorized_keys~/.ssh/authorized_keysPermission denied (publickey)Permission denied (publickey)

O handshake, passo a passoThe handshake, step by step

ClienteClient ServidorServer em claroin the clear troca de chaves (autentica o servidor)key exchange (authenticates the server) TUDO daqui para baixo vai cifradoEVERYTHING below this line is encrypted ① conecta na porta 22 · versões① connects to port 22 · versions SSH-2.0-OpenSSH_…SSH-2.0-OpenSSH_… ② lista de algoritmos aceitos (KEXINIT)② lists of accepted algorithms (KEXINIT) ③ metade pública efêmera do cliente③ client’s ephemeral public half ④ metade do servidor + chave pública do host + assinatura④ server’s half + host public key + signature ⑤ usuário "ana" + chave pública id_ed25519.pub⑤ user "ana" + public key id_ed25519.pub ⑥ essa chave está em authorized_keys? sim⑥ is that key in authorized_keys? yes ⑦ assinatura (com a privada) sobre o ID da sessão⑦ signature (with the private key) over the session ID ⑧ servidor verifica com a pública → autenticado⑧ server verifies with the public key → authenticated ⑨ abre canal: shell, comando, sftp, túnel⑨ opens channel: shell, command, sftp, tunnel
Primeiro o cliente confere o servidor (passos 3 e 4, com known_hosts); depois, já dentro do túnel cifrado, o servidor confere o cliente (passos 5 a 8).First the client checks the server (steps 3 and 4, with known_hosts); then, already inside the encrypted tunnel, the server checks the client (steps 5 to 8).
A primeira conexão é um ato de fé (TOFU, “trust on first use”). Na primeira vez o SSH mostra a impressão da chave do servidor e pergunta se você confia. Se você aceitar sem conferir, um intermediário na primeira conexão passa despercebido. Em servidores importantes, confira a impressão por outro canal (console do provedor, quem administra).The first connection is an act of faith (TOFU, “trust on first use”). The first time, SSH shows the server key’s fingerprint and asks whether you trust it. If you accept without checking, a man in the middle on the first connection goes unnoticed. For important servers, check the fingerprint through another channel (provider console, the administrator).

Mão na massaHands-on

# 1. generate the pair: id_ed25519 (private) and id_ed25519.pub (public)
ssh-keygen -t ed25519 -C "gustavo@laptop"

# 2. show the fingerprint of the public key
ssh-keygen -lf ~/.ssh/id_ed25519.pub

# 3. install the public key on the server (it goes into ~/.ssh/authorized_keys)
ssh-copy-id -i ~/.ssh/id_ed25519.pub ana@server.example.com

# 4. sign in: the private key signs the challenge, it is never sent
ssh ana@server.example.com

# 5. debug: -v shows every key offered and every step
ssh -v ana@server.example.com
  • Defina uma passphrase ao gerar a chave: ela cifra o arquivo da privada no disco. Sem ela, quem copiar o arquivo ganha o acesso.Set a passphrase when generating the key: it encrypts the private-key file on disk. Without it, whoever copies the file gets the access.
  • Permissões importam: chmod 700 ~/.ssh e chmod 600 na privada e no authorized_keys. O SSH recusa chaves legíveis por outros.Permissions matter: chmod 700 ~/.ssh and chmod 600 on the private key and on authorized_keys. SSH refuses keys readable by others.
  • Uma chave por aparelho: assim, perdeu o notebook, remova só a pública dele dos servidores.One key per device: that way, if you lose the laptop, you remove only its public key from the servers.

Endurecendo o servidorHardening the server

# /etc/ssh/sshd_config  (check the manual for your distribution)
PubkeyAuthentication yes
PasswordAuthentication no     # keys only: removes password guessing
PermitRootLogin no            # sign in as a normal user, then use sudo

Depois de alterar, recarregue o serviço (sshd ou ssh, conforme a distribuição) e teste numa segunda sessão antes de fechar a primeira: um erro aqui pode trancar você fora.After changing it, reload the service (sshd or ssh, depending on the distribution) and test in a second session before closing the first: a mistake here can lock you out.

ssh-agent, bastion e ProxyJumpssh-agent, bastion and ProxyJump

Seu computadorYour computer ssh-agentssh-agent guarda a chave já destravadaholds the already unlocked key cliente sshssh client pede: "assine isto"asks: "sign this" BastionBastion (jump host)(jump host) Servidor internoInternal server sem IP públicono public IP 11 22 ssh -J bastion internal A assinatura acontece no seu computador; a chave não vai para o bastion.Signing happens on your computer; the key does not go to the bastion. O túnel 2 passa DENTRO da conexão 1, cifrado de ponta a ponta até o servidor interno.Tunnel 2 runs INSIDE connection 1, encrypted end to end to the internal server. Prefira -J (ProxyJump). Evite o agent forwarding (-A) em hosts que você não controla:Prefer -J (ProxyJump). Avoid agent forwarding (-A) on hosts you do not control: quem é root lá pode usar seu agent enquanto você estiver conectado.anyone who is root there can use your agent while you are connected.
O agent digita a passphrase uma única vez e assina por você. Com ProxyJump você chega a servidores internos sem expor a chave privada.The agent unlocks the passphrase once and signs for you. With ProxyJump you reach internal servers without exposing the private key.
# start an agent and load the key (the passphrase is asked once)
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
ssh-add -l                       # lists the keys the agent holds

# reach an internal server through a bastion, without forwarding the agent
ssh -J ana@bastion.example.com ana@10.0.1.20

SSH com o GitHubSSH with GitHub

Cadastre a pública em Settings → SSH and GPG keys e teste com ssh -T git@github.com. O mesmo par pode também assinar commits (Git 2.34 ou mais novo).Register the public key under Settings → SSH and GPG keys and test with ssh -T git@github.com. The same pair can also sign commits (Git 2.34 or newer).

git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true

Onde isso aparece no dia a diaWhere this shows up day to day

SituaçãoSituationQuem tem a privadaWho holds the private keyO que a pública fazWhat the public key doesParte simétricaSymmetric part
HTTPSHTTPSO servidor (chave do certificado)The server (certificate key)Navegador verifica a assinatura do handshakeBrowser verifies the handshake signatureChave de sessão do TLS (AES-GCM, ChaCha20)TLS session key (AES-GCM, ChaCha20)
SSHSSHVocê (login) e o servidor (host key)You (login) and the server (host key)authorized_keys e known_hostsauthorized_keys and known_hostsTúnel cifrado da sessãoThe session’s encrypted tunnel
Passkey / app de bancoPasskey / banking appO chip do seu aparelhoYour device’s chipO servidor verifica a assinatura do desafioThe server verifies the challenge signatureSessão (cookie/token) e TLSSession (cookie/token) and TLS
JWT / OIDCJWT / OIDCO provedor de identidade (GitHub, Google)The identity provider (GitHub, Google)Quem recebe o token baixa a pública (JWKS) e verificaWhoever receives the token downloads the public key (JWKS) and verifiesTLS na chamadaTLS on the call
Commit assinadoSigned commitVocêYouGitHub verifica e mostra “Verified”GitHub verifies and shows “Verified”——
Chaves de acesso da AWSAWS access keysNinguém: é simétrico (HMAC). A secret key fica em dois lugares.Nobody: it is symmetric (HMAC). The secret key lives in two places.——A requisição é assinada com HMAC-SHA-256 (SigV4)The request is signed with HMAC-SHA-256 (SigV4)
Por que o OIDC do GitHub Actions é melhor que chaves da AWS. As chaves de acesso são simétricas: quem as copia assina como você, para sempre. No OIDC, o GitHub assina cada token com uma chave privada que só ele tem, e a AWS só precisa da pública para verificar; o job recebe credenciais temporárias que expiram. Veja GitHub para AWS com OIDC.Why GitHub Actions OIDC beats AWS access keys. Access keys are symmetric: whoever copies them signs as you, forever. With OIDC, GitHub signs each token with a private key only it holds, and AWS needs only the public key to verify; the job gets temporary credentials that expire. See GitHub to AWS with OIDC.

GlossárioGlossary

TermoTermO que éWhat it is
CriptografiaTécnicas matemáticas para proteger sigilo, integridade e autenticidade.Mathematical techniques to protect secrecy, integrity and authenticity.
Texto claro / texto cifradoO dado legível e o dado embaralhado pela cifra.The readable data and the data scrambled by the cipher.
ChaveUm número (ou bytes) que controla a cifra. Quem tem a chave certa desfaz o embaralhamento.A number (or bytes) that controls the cipher. Whoever holds the right key undoes the scrambling.
Chave pública / privadaAs duas metades de um par. A pública pode ser distribuída; a privada nunca sai do dono.The two halves of a pair. The public one may be shared; the private one never leaves its owner.
Hash / resumo (digest)Impressão digital de tamanho fixo, sem volta. Ex.: SHA-256.Fixed-size fingerprint, no way back. E.g. SHA-256.
Assinatura digitalProva de autoria e integridade feita com a chave privada e conferida com a pública.Proof of authorship and integrity made with the private key and checked with the public one.
Certificado (X.509)Chave pública + identidade (domínio), assinada por uma CA.Public key + identity (domain), signed by a CA.
CA (autoridade certificadora)Entidade em quem o sistema confia para assinar certificados. Ex.: Let’s Encrypt.Entity the system trusts to sign certificates. E.g. Let’s Encrypt.
Desafio (nonce)Valor aleatório usado uma única vez para que a resposta não possa ser reaproveitada.Random value used only once so the answer cannot be reused.
Chave efêmera / forward secrecyChave criada só para uma conexão. Garante que roubar chaves futuras não decifra conversas passadas.Key created just for one connection. Ensures that stealing later keys does not decrypt past conversations.
Impressão digital (fingerprint)Hash curto de uma chave pública, para conferir a olho. Ex.: SHA256:… no SSH.Short hash of a public key, for checking by eye. E.g. SHA256:… in SSH.
PassphraseSenha que cifra o arquivo da chave privada no disco.Password that encrypts the private-key file on disk.
Enclave / TPM / StrongBoxHardware seguro que guarda a chave privada e assina sem entregá-la.Secure hardware that keeps the private key and signs without handing it out.
SessãoEstado “você já entrou”, guardado no servidor ou num token, que dispensa nova prova a cada requisição.The “you are already in” state, kept on the server or in a token, which avoids a new proof on every request.
TOFUTrust on first use: confiar na chave vista na primeira conexão e alertar se mudar depois.Trust on first use: trust the key seen on the first connection and warn if it changes later.

Erros comuns e como resolverCommon errors and how to fix them

SintomaSymptomCausa provávelLikely causeO que fazerWhat to do
Permission denied (publickey)A pública não está no servidor, o usuário está errado ou o SSH ofereceu outra chave.The public key is not on the server, the user is wrong, or SSH offered another key.Rode ssh -v e veja as chaves oferecidas; confira authorized_keys, o nome do usuário e use -i ou IdentityFile.Run ssh -v and look at the keys offered; check authorized_keys, the user name and use -i or IdentityFile.
UNPROTECTED PRIVATE KEY FILE!A privada está legível por outros usuários.The private key is readable by other users.chmod 600 ~/.ssh/id_ed25519 e chmod 700 ~/.ssh.chmod 600 ~/.ssh/id_ed25519 and chmod 700 ~/.ssh.
REMOTE HOST IDENTIFICATION HAS CHANGED!A chave do servidor mudou: reinstalação, IP reaproveitado... ou um intermediário.The server key changed: reinstall, reused IP... or a man in the middle.Não ignore. Confirme com quem administra o servidor; só então ssh-keygen -R host e reconecte.Do not ignore it. Confirm with whoever runs the server; only then ssh-keygen -R host and reconnect.
Too many authentication failuresO agent oferece chaves demais antes da certa.The agent offers too many keys before the right one.Use IdentitiesOnly yes e IdentityFile no ~/.ssh/config.Use IdentitiesOnly yes and IdentityFile in ~/.ssh/config.
Colei a pública no lugar da privada (ou o contrário)Confusão entre id_ed25519 e .pub.Mixing up id_ed25519 and .pub.A .pub é a que se compartilha. Para conferir se um par combina: ssh-keygen -y -f id_ed25519 imprime a pública correspondente.The .pub is the one you share. To check a pair matches: ssh-keygen -y -f id_ed25519 prints the matching public key.
Load key … invalid formatArquivo da privada corrompido: quebra de linha trocada, cabeçalho cortado, falta a linha final.Corrupted private-key file: changed line endings, cut header, missing final newline.Recopie o arquivo inteiro, sem editar, ou gere um novo par.Copy the whole file again, unedited, or generate a new pair.
A privada foi parar no repositório, num chat ou num logVazamento: considere-a comprometida.Leak: consider it compromised.Remova a pública dos servidores e da conta do GitHub, gere um par novo. Apagar o commit não basta: o histórico e os clones guardam a cópia.Remove the public key from servers and the GitHub account, generate a new pair. Deleting the commit is not enough: history and clones keep the copy.
Navegador: NET::ERR_CERT_COMMON_NAME_INVALID ou certificado expiradoO nome no certificado não cobre o domínio acessado, ou a validade acabou.The name in the certificate does not cover the domain visited, or the validity ended.Confira os nomes (SAN) e a data; renove; instale também o certificado intermediário.Check the names (SAN) and the date; renew; also install the intermediate certificate.
Tentei “cifrar com a privada” para proteger dadosConfundir assinatura com cifragem.Mixing up signing with encrypting.Para sigilo, cifre com a pública do destinatário (ou use uma chave simétrica). Para provar autoria, assine.For secrecy, encrypt with the recipient’s public key (or use a symmetric key). To prove authorship, sign.
JWT aceito mesmo com a assinatura alteradaO verificador aceita alg: none ou troca RS256 por HS256 usando a pública como segredo.The verifier accepts alg: none or swaps RS256 for HS256 using the public key as the secret.Fixe o algoritmo esperado na verificação e use bibliotecas mantidas (RFC 8725).Pin the expected algorithm when verifying and use maintained libraries (RFC 8725).
Perdi o celular com a passkeyA privada ficou no aparelho.The private key was on the device.Use outra passkey ou os códigos de backup, e revogue a credencial antiga no servidor.Use another passkey or the backup codes, and revoke the old credential on the server.

Cola e revisãoCheat sheet and review

ColaCheat sheet

Quero…I want…FaçaDo
que ninguém leia os dados no caminhonobody to read the data on the wayCifre: TLS no tráfego, AES-GCM em dados em repouso.Encrypt: TLS for traffic, AES-GCM for data at rest.
provar que um arquivo ou token veio de mimto prove a file or token came from meAssine com a privada; quem recebe verifica com a pública.Sign with the private key; the receiver verifies with the public one.
detectar se algo foi alteradoto detect tamperingCompare hashes (ou use assinatura/MAC se houver adversário).Compare hashes (or use a signature/MAC if there is an adversary).
entrar num servidor por SSHto log in to a server over SSHssh-keygen -t ed25519, ssh-copy-id, desligar senha no servidor.ssh-keygen -t ed25519, ssh-copy-id, turn passwords off on the server.
login sem senha em um apppassword-free sign-in in an appPasskey/WebAuthn: o aparelho assina um desafio; guarde só a pública.Passkey/WebAuthn: the device signs a challenge; store only the public key.
manter o usuário logado sem pedir assinatura sempreto keep the user signed in without asking for a signature every timeSessão com cookie seguro ou token curto + refresh; reautentique em ações sensíveis.Session with a secure cookie or short token + refresh; re-authenticate on sensitive actions.
conferir um servidor SSH novoto check a new SSH serverCompare a impressão (fingerprint) por outro canal antes de aceitar.Compare the fingerprint over another channel before accepting.

Perguntas de revisãoReview questions

PerguntaQuestionRespostaAnswer
Por que o TLS e o SSH combinam criptografia assimétrica e simétrica?Why do TLS and SSH combine asymmetric and symmetric cryptography?A assimétrica resolve combinar uma chave em público (e prova identidade), mas é lenta; a simétrica é rápida para o volume de dados. Usa-se a primeira para acordar a chave e a segunda para os dados.Asymmetric solves agreeing on a key in public (and proves identity) but is slow; symmetric is fast for the volume of data. The first agrees on the key, the second carries the data.
Num login por chave no aparelho, o que trafega e o que nunca sai do aparelho?In a device-key sign-in, what travels and what never leaves the device?Trafegam o desafio e a assinatura (e, no cadastro, a chave pública). A chave privada e a biometria nunca saem do aparelho; o servidor só verifica com a pública.The challenge and the signature travel (and, at enrollment, the public key). The private key and the biometric never leave the device; the server only verifies with the public key.
Por que existe a sessão depois da assinatura, e qual o risco dela?Why does the session exist after the signature, and what is its risk?Para não assinar a cada requisição. O risco: é um portador, e um cookie ou token roubado vale até expirar; por isso prazos curtos, revogação e step-up.To avoid signing on every request. The risk: it is a bearer, and a stolen cookie or token works until it expires; hence short lifetimes, revocation and step-up.
O que known_hosts e authorized_keys provam, cada um?What do known_hosts and authorized_keys each prove?known_hosts: você confere que o servidor é o mesmo de antes. authorized_keys: o servidor confere que a sua chave está autorizada a entrar.known_hosts: you check that the server is the same as before. authorized_keys: the server checks that your key is allowed in.