Alice sends Bob a contract over the internet. (Crypto books always call the two people Alice and Bob.) Eve copies everything on the wire. Mallory can also change it. HTTPS, e-signed PDFs and SNAP payment APIs all beat them with one trick: two keys, one public and one private. An e-signed PDF is a contract signed inside the file. SNAP is Indonesia's standard for bank APIs.
Follow Alice through one secret message, one signed contract, one payment API call and one HTTPS page. After this post you can:
- encrypt and sign a file with
openssl - sign a SNAP payment API call
- read what
opensslprints when it checks an HTTPS site
openssl is a command-line tool for keys, hashes and encryption. macOS and most Linux have it.
Two keys: lock and open#
First, a secret message: Bob wants to send Alice "meet at 7". Words you need:
- To encrypt is to turn readable data into scrambled data, the ciphertext.
- To decrypt is to turn it back.
- A symmetric key is one shared password: the same key locks and opens.
A symmetric key would have to travel to Bob first, and Eve would copy it on the way.
So Alice makes a key pair. Think of open padlocks. She hands them to anyone who asks: that is the public key. Anyone can close one on a box. Only her own key opens it: that is the private key.
- Alice makes a public key and a private key.
- She sends Bob the public key. Eve copies it.
- Bob locks the message with it. Eve copies that too.
- Eve can't open it. Not even Bob can: he only has the public key.
- Only Alice's private key opens it.
- Public key: give it to anyone.
- Private key: never leaves your machine, because whoever has it can act as you. Never commit it to git, paste it in a chat or attach it to a ticket.
- Getting the private key from the public key would take normal computers far too long.
Before the first command:
- RSA is a very common kind of key pair.
- 2048 bits is the key length. Longer keys are harder to break, and 2048 is common today.
- The private key file holds everything needed to rebuild the public key, so
pkey -pubouttakes the public half out. - PEM is the text format you see between the
BEGINandENDlines.
# Alice: make a private key, then take the public key out of it
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out private.pem
openssl pkey -in private.pem -pubout -out public.pem
head -1 private.pem public.pem
# Bob: encrypt with Alice's public key (-pubin: the key file is a public key)
echo "meet at 7" > secret.txt
openssl pkeyutl -encrypt -pubin -inkey public.pem -in secret.txt -out secret.enc
wc -c secret.enc
# Alice: decrypt with her private key
openssl pkeyutl -decrypt -inkey private.pem -in secret.enc
==> private.pem <==
-----BEGIN PRIVATE KEY-----
==> public.pem <==
-----BEGIN PUBLIC KEY-----
256 secret.enc
meet at 7
A 2048-bit RSA key always gives 256 bytes of ciphertext. With this key, the message itself must be under 256 bytes. That matters later, for HTTPS.
Someone copies secret.enc and public.pem. Can they read the message?
Signatures: prove who sent it#
Now the contract. Alice sends contract.txt: "pay Bob 100". Mallory wants it to say 900. To catch her, Bob needs two tools: a hash and a signature.
A hash is a short fingerprint of any data. The same data always gives the same hash, and you can't get the data back from it. SHA-256 is a common one. Change one digit:
echo "pay Bob 100" > contract.txt
openssl dgst -sha256 contract.txt
echo "pay Bob 900" > contract.txt
openssl dgst -sha256 contract.txt
SHA256(contract.txt)= 79303b6eeb3938470f98f38ed62d4fb14a664388bea3d9b01efb047360e9e43f
SHA256(contract.txt)= 152e949233ff5e312fa02d1e08996182cc5b6426379bf3a46dff485a3efc960a
A whole new hash. (Some openssl versions print the first part a bit differently.) But Mallory can hash her version too, so a hash alone proves nothing. A signature is a value made from the hash and Alice's private key. Only her private key can make it, and anyone can check it with her public key:
- Alice hashes the file and signs the hash with her private key.
- She sends contract.txt and contract.sig.
- Bob hashes it and checks with Alice's public key. Match.
- Next time, Mallory changes 100 to 900.
- New hash, so the same check fails.
echo "pay Bob 100" > contract.txt
# Alice signs with her private key (hash + sign in one step)
openssl dgst -sha256 -sign private.pem -out contract.sig contract.txt
# Bob verifies with Alice's public key
openssl dgst -sha256 -verify public.pem -signature contract.sig contract.txt
# someone changes the file, Bob verifies again
echo "pay Bob 900" > contract.txt
openssl dgst -sha256 -verify public.pem -signature contract.sig contract.txt
Verified OK
Verification Failure
Same two keys, opposite directions:
| Encryption | Signature | |
|---|---|---|
| Lock / sign with | receiver's public key | sender's private key |
| Open / check with | receiver's private key | sender's public key |
| Proves | only the receiver can read it | who signed, nothing changed |
| Hides the data? | yes | no, sign and encrypt for both |
Mallory changes the file and signs it with her own private key. Bob checks it with Alice's public key. What happens?
Certificates: prove whose key it is#
Mallory sends Bob her own public key: "this is Alice's key". A key file has no name on it, so Bob can't tell. A certificate puts a name on a key. It holds a name, a public key and an expiry date. A certificate authority (CA) checks who you are and signs it. PDF readers and operating systems come with a list of CA certificates they already trust.
- Alice sends a CSR (signing request): her name + public key.
- The CA checks her ID, then signs with its own private key.
- Alice gets her certificate. Her private key never left.
- She sends Bob the signed contract and the certificate.
- Bob trusts the CA, so he trusts the key that checks the file.
You play every role: the CA, Alice and Bob. X.509 is the standard certificate format, so the command is openssl x509. CN (common name) is the name field.
# 1. the CA makes its own key (ca.key) and a certificate for itself (ca.crt)
# -newkey rsa:2048: make a new 2048-bit RSA key for the CA
# -x509: make a certificate, not a request
# -nodes: no password on ca.key (fine for a toy, never for a real CA)
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 365 -subj "/CN=Toy CA"
# 2. Alice makes a CSR from her private key, with her name as the CN
openssl req -new -key private.pem -out alice.csr -subj "/CN=Alice"
# 3. the CA signs Alice's certificate with ca.key
# -CAcreateserial: give the certificate a serial number, so the CA can tell its certificates apart
openssl x509 -req -in alice.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out alice.crt -days 365
# 4. anyone who trusts the CA can check Alice's certificate
openssl verify -CAfile ca.crt alice.crt
openssl x509 -in alice.crt -noout -subject -issuer
# 5. Alice writes the contract again (the last test left it at 900) and signs it
echo "pay Bob 100" > contract.txt
openssl dgst -sha256 -sign private.pem -out contract.sig contract.txt
# 6. Bob takes Alice's public key out of her certificate and checks the contract
# -pubkey -noout: print only the public key from the certificate
openssl x509 -in alice.crt -pubkey -noout > alice-public.pem
openssl dgst -sha256 -verify alice-public.pem -signature contract.sig contract.txt
alice.crt: OK
subject= /CN=Alice
issuer= /CN=Toy CA
Verified OK
subject is who it's for, issuer is who signed it. A real CA keeps its key very safe. Our ca.crt plays the part of one of those trusted CA certificates.
E-signed PDFs: the gap trick#
A pasted picture of a signature proves nothing, because anyone can copy it. A real e-signature (also called a digital signature) is the signature above, stored inside the PDF with the signer's certificate. The app leaves a gap, hashes everything else, and fills the gap after. (If the gap were hashed too, filling it later would change the hash.)
- Bob's reader finds the signature and certificate in the gap
- Checks the CA signature and the expiry date
- Takes Alice's public key out of the certificate
- Hashes the PDF again, everything except the gap
- Checks Alice's signature against that hash: valid
Alice signs a PDF. Later someone edits one number in it. What breaks?
SNAP: sign each payment API call#
Alice's shop calls her bank's payment API. In Indonesia that's SNAP (Standar Nasional Open API Pembayaran), Bank Indonesia's standard for transfers, virtual accounts and QR payments. The bank is the provider, the shop is the partner.
Words you need:
- An access token is a short-lived pass. The bank gives it to the shop, and the shop shows it on every call.
- A client secret is a symmetric key that only the shop and the bank know. The bank gives it to the shop when the shop signs up.
- An HMAC is a signature made with a shared secret instead of a private key.
SNAP signs twice. The key pair signs the request for a token. The client secret signs every call after that.
- The shop signs its ID and the time with its private key.
- It sends the signature with the ID and the time.
- The bank checks it with the registered public key. Valid: a token.
- Every call after: an HMAC signed with the shared client secret.
- Mallory resends a copied 10:00 request at 10:30. The time inside still says 10:00, so the bank refuses it. She can't change the time without the key.
The access token: SHA256withRSA#
Usually you make the key pair yourself (like private.pem above). You give the provider only the public key, once, when you register.
The provider gives you a client ID. It goes in the X-CLIENT-KEY header. Despite the name, it holds an ID, not a secret. The provider uses it to find your public key again.
The signed text is the client ID and X-TIMESTAMP, joined by a | character. SHA256withRSA means hash with SHA-256, then sign with the RSA private key: what openssl dgst -sha256 -sign did. Base64 writes the bytes as plain letters and numbers, so they fit in an HTTP header.
<client ID>|<X-TIMESTAMP>
demo-client-id|2026-10-29T10:00:00+07:00
The path is /v1.0/access-token/b2b. b2b means business to business: your server calls the provider's server. Some providers put extra text before the path, or use another timestamp format, so check their docs. All IDs here are toy values.
import crypto from 'node:crypto';
import fs from 'node:fs';
const clientId = 'demo-client-id'; // X-CLIENT-KEY, from your provider
const timestamp = '2026-10-29T10:00:00+07:00'; // X-TIMESTAMP, in real code: the current time
const privateKey = fs.readFileSync('private.pem', 'utf8');
const stringToSign = `${clientId}|${timestamp}`;
// SHA256withRSA: hash with SHA-256, sign with the RSA private key
const signature = crypto.sign('sha256', Buffer.from(stringToSign), privateKey).toString('base64');
const res = await fetch('https://bank.example/v1.0/access-token/b2b', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-TIMESTAMP': timestamp,
'X-CLIENT-KEY': clientId,
'X-SIGNATURE': signature,
},
body: JSON.stringify({ grantType: 'client_credentials' }), // the standard value for a server-to-server token
signal: AbortSignal.timeout(10_000), // never wait forever on a bank
});
const { accessToken } = await res.json();
The provider rebuilds the text from your headers:
const ok = crypto.verify(
'sha256',
Buffer.from(`${clientIdHeader}|${timestampHeader}`), // rebuilt from your headers
partnerPublicKey, // the public key you registered
Buffer.from(signatureHeader, 'base64'),
);
// ok is true: send back a token
// ok is false: answer 401 Unauthorized
{
"responseCode": "2007300",
"responseMessage": "Successful",
"accessToken": "eyJhbGciOi...",
"tokenType": "Bearer",
"expiresIn": "900"
}
2007300= HTTP200+ service73(access token) + case00.- In this example the token lives 900 seconds, 15 minutes (
expiresIn). Reuse it until it expires, don't ask for a new one per call. Send it asAuthorization: Bearer <token>. "Bearer" means whoever holds it may use it. - The timestamp is inside the signed text. Mallory can copy a request, but she can't change its time without your private key. So the provider can refuse a request with an old time.
- A 401 with the right client ID? Most likely
X-TIMESTAMPis not the exact text you signed. The body is not part of this signature, so the problem is not in the body. - Sending your public key to the provider by email is safe: it can only check signatures. Just make sure they get your real one.
Your token call gets 401. The client ID is right. What do you check first?
Every call: HMAC-SHA512#
Now every call is signed with the client secret, as an HMAC. The text you sign has five parts, joined with colons:
<HTTP method>:<path>:<access token>:<hash of the minified body>:<X-TIMESTAMP>
Minify the body first: plain JSON.stringify(body), so no spaces or new lines between the parts. Then two hashes, as the diagram below shows. The body hash is written as lowercase hex (only the characters 0-9 and a-f). HMAC-SHA512 is an HMAC with the SHA-512 hash inside.
import crypto from 'node:crypto';
const clientSecret = process.env.SNAP_CLIENT_SECRET; // from your provider, never in code
const accessToken = 'eyJhbGciOi...'; // from the token call
const timestamp = '2026-10-29T10:01:00+07:00';
const path = '/v1.0/balance-inquiry';
const body = { partnerReferenceNo: 'ref-0001', accountNo: '1234567890' };
const bodyText = JSON.stringify(body); // minified, no spaces
const bodyHash = crypto.createHash('sha256').update(bodyText).digest('hex'); // lowercase hex
const stringToSign = `POST:${path}:${accessToken}:${bodyHash}:${timestamp}`;
const signature = crypto.createHmac('sha512', clientSecret).update(stringToSign).digest('base64');
await fetch(`https://bank.example${path}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
'X-TIMESTAMP': timestamp,
'X-SIGNATURE': signature,
'X-PARTNER-ID': 'demo-partner-id', // your partner ID, from your provider
'X-EXTERNAL-ID': '41807553358950093184162180797837', // a new ID for every request
'CHANNEL-ID': '95221', // a channel code, from your provider
},
body: bodyText, // send the exact text you hashed
signal: AbortSignal.timeout(10_000),
});
- Sign the exact path you call, prefix included.
X-EXTERNAL-IDis usually unique within the day, so the provider spots repeats.- The secret lives in an env variable or a secret manager, never in git.
The provider rebuilds the text, makes its own HMAC and compares the two. timingSafeEqual compares in constant time: it always takes the same time. So an attacker can't use the time of a wrong guess to find the signature, one byte at a time.
// provider side: same colon text, same secret, then compare
const expected = crypto.createHmac('sha512', clientSecret).update(rebuiltStringToSign).digest('base64');
const ok = expected.length === signatureHeader.length
&& crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signatureHeader)); // compare without leaking timing
An HMAC can't tell which side made it, because both sides know the secret. Nobody else does, so that's fine. If Mallory changes accountNo in a copied request, the body hash changes, and she needs the secret to sign again.
| Access token | Transaction call | |
|---|---|---|
| Method | SHA256withRSA | HMAC-SHA512 |
| Key | your private key | shared client secret |
| Signed text | client ID, timestamp | method, path, token, body hash, timestamp |
| How often | once per token | every call |
Your code hashes JSON.stringify(body, null, 2), JSON with spaces and new lines. The provider says the signature is invalid. Why?
Diffie-Hellman: a secret nobody sent#
In SNAP, the bank gave the shop the client secret ahead of time. A browser has no such secret: it meets a website for the first time. TLS is the protocol under HTTPS that sets up the safe connection, and TLS 1.3 is the current version. It starts with a handshake: the first messages two sides send to set up a safe connection.
The page data is encrypted with a session key: a fast symmetric key for one connection, thrown away after. How do two strangers get the same one while Eve listens? Sending it in the open leaks it. Old TLS (before 1.3) used the first chapter's trick: a session key is small, so it fits the RSA size limit. Watch the weak spot:
- Monday: the session key goes out, locked with the server's public key.
- Eve records it all. She can't read it yet.
- Next year the server's private key leaks.
- Eve opens the old session key and reads Monday.
Diffie-Hellman (DH) is named after the two people who published it. It sends only public numbers, and both sides compute the same secret. The session key is made from that secret.
Think of paint. Both sides agree on yellow in public. Each adds a secret colour and sends the mix. Then each adds their own secret colour to the mix they got. Both end with the same brown. Eve sees the mixes, but unmixing paint is too hard. Real DH uses math that is easy to do and hard to undo.
The math you need:
5^3means 5 × 5 × 5 = 125.modis the remainder after a division:125 mod 23 = 10, because 125 = 5 × 23 + 10.p = 23is a public number we divide by for mod.g = 5is a public number we raise to a power (the 5 in5^3).
In the widget, Alice and Bob stand in for the browser and the server.
- Alice and Bob agree in public on p = 23, g = 5. Eve sees them too.
- Alice picks 6 and keeps it secret.
- Bob picks 15 and keeps it secret.
- Alice sends 5^6 mod 23 = 8.
- Bob sends 5^15 mod 23 = 19.
- Alice: 19^6 mod 23 = 2. Bob: 8^15 mod 23 = 2.
- Eve saw 23, 5, 8, 19. Never 2.
In Python, pow(g, a, p) is g^a mod p (Python's ^ means something else).
p, g = 23, 5 # public, everyone sees these
a, b = 6, 15 # secret: Alice picks a, Bob picks b
A = pow(g, a, p) # Alice sends 8
B = pow(g, b, p) # Bob sends 19
print(pow(B, a, p)) # Alice computes 2
print(pow(A, b, p)) # Bob computes 2
- Alice computes
(g^b)^aand Bob computes(g^a)^b. Both areg^(a×b) mod p, so they match. - With numbers this small, Eve can try every secret. Real DH uses huge numbers, or a different kind of math called elliptic curves.
Forward secrecy means a key that leaks later can't open old recordings. TLS 1.3 makes new DH secrets for every handshake, and the server's private key never helps make them. TLS 1.3 removed the old way (locking the session key with the server's public key). Same leak as before, new ending:
- Monday: the browser and the server swap public DH numbers.
- Eve records it all, like before.
- The connection ends. The browser throws its DH secret away.
- The server throws its DH secret away too.
- Next year the server's private key leaks.
- Eve tries it on Monday's recording. It opens nothing: that key never made the session key.
Eve recorded 23, 5, 8 and 19. What else does she need?
HTTPS: one handshake, every idea#
DH can't tell who is on the other side. Mallory runs the café Wi-Fi, a classic man in the middle:
- Alice starts DH with example.com. Mallory answers.
- Mallory runs a second DH with the real server.
- She decrypts, reads, re-encrypts. Nobody notices.
- Fix: the server sends its certificate and signs the handshake.
- Mallory can copy the certificate. She can't sign.
Three words first:
- The trust store is the list of CA certificates your system or browser already trusts.
- A root CA is a CA whose certificate sits in the trust store.
- The certificate chain is the site's certificate plus the CA certificates above it, up to a root CA.
The browser checks three things. Each of Mallory's tricks fails one of these checks:
| Browser checks | Mallory tries | Fails because |
|---|---|---|
| 1. The chain ends at a root CA in the trust store | her own certificate for example.com | no trusted CA signed it |
| 2. The name matches the site | a real certificate for her own site | wrong name |
| 3. The handshake signature fits the certificate key | a copy of the real certificate | no private key |
# -servername: tell the server which site you want (one server can host many sites)
# </dev/null: send nothing, so openssl quits after the handshake
openssl s_client -connect example.com:443 -servername example.com </dev/null
A cipher suite is the set of algorithms both sides agree on for one connection. Below is part of the output on a Mac (LibreSSL, the openssl that comes with macOS) in October 2026. Yours will differ, because certificates change.
0 s:/CN=example.com
i:/C=US/O=SSL Corporation/CN=Cloudflare TLS Issuing ECC CA 3
1 s:/C=US/O=SSL Corporation/CN=Cloudflare TLS Issuing ECC CA 3
i:/C=US/O=SSL Corporation/CN=SSL.com TLS Transit ECC CA R2
2 s:/C=US/O=SSL Corporation/CN=SSL.com TLS Transit ECC CA R2
i:/C=US/O=SSL Corporation/CN=SSL.com TLS ECC Root CA 2022
Server Temp Key: ECDH, X25519, 253 bits
Protocol : TLSv1.3
Cipher : AEAD-CHACHA20-POLY1305-SHA256
Verify return code: 0 (ok)
s:subject (who it's for),i:issuer (who signed it).Ois the organization,Cthe country.- Each certificate's
i:is thes:of the next one. That is the chain from the diagram, read from the site up to the root CA. - 1 and 2 are intermediate CAs: CAs between the root and the site. They do the daily signing, so the root key stays locked away. Many sites have one, this one has two.
ECDH, X25519: the DH from the last chapter. ECDH is DH with elliptic curves, and X25519 is one common curve.Cipher: the cipher suite. ChaCha20 is the fast symmetric encryption method (cipher) for the page.AEAD-CHACHA20-POLY1305-SHA256is LibreSSL's name for the standardTLS_CHACHA20_POLY1305_SHA256.0 (ok): every check passed.- You can skip the other names for now (AEAD, POLY1305, 253 bits).
HTTPS is plain HTTP sent inside TLS. TLS 1.3 needs one round trip (one message there, one answer back) before the first HTTP request:
- ClientHello: cipher suites + browser DH number
- ServerHello: chosen cipher suite + server DH number
- Both compute the DH secret. Everything after is encrypted
- Server sends its certificate chain
- CertificateVerify: server signs the handshake with its private key
- Finished: the server sends a value made from every handshake message, so the browser can see nothing was changed
- Browser checks chain, name and signature, sends its Finished
- HTTP request goes out, encrypted with the session key
Where is the server's private key used in a TLS 1.3 handshake?
If a check fails, Chrome stops and shows one of these errors:
| Chrome error | Failed check |
|---|---|
NET::ERR_CERT_AUTHORITY_INVALID | chain doesn't end at a trusted CA |
NET::ERR_CERT_COMMON_NAME_INVALID | name doesn't match the site |
NET::ERR_CERT_DATE_INVALID | expired, or not valid yet |
To see the dates behind NET::ERR_CERT_DATE_INVALID, print them yourself:
# 2>/dev/null: hide the extra messages openssl prints
# openssl x509 -noout -dates: print only the certificate's start and end dates
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -dates
The output in November 2026 (yours will differ). Before notBefore or after notAfter, Chrome shows the date error.
notBefore=Sep 26 22:49:11 2026 GMT
notAfter=Dec 25 22:56:35 2026 GMT
Recap#
| Tool | Job | Where it showed up |
|---|---|---|
| Key pair | public locks, private opens | "meet at 7" |
| Signature | who signed, nothing changed | Alice's contract, the server's CertificateVerify |
| Certificate | a CA says whose key it is | alice.crt, the PDF, the site chain |
| HMAC | a signature with a shared secret | every SNAP call |
| Diffie-Hellman | one secret, never sent | the TLS 1.3 hellos |
| Session key | fast symmetric encryption | the page |
Try it yourself, one per chapter:
-
Encrypt a short message of your own with
public.pem, then decrypt it withprivate.pem. -
Sign one of your own files, change one letter, and verify again.
-
Read the whole certificate with
openssl x509 -in alice.crt -noout -textand find the CN. -
Check your own token signature like the provider does. Add this after the token code and check that it prints
true:console.log(crypto.verify('sha256', Buffer.from(stringToSign), fs.readFileSync('public.pem', 'utf8'), Buffer.from(signature, 'base64'))); -
Change
aandbin the Python code and check that both sides still match. -
Run
openssl s_clienton a site you use every day. Find the DH line, the chain and the cipher, and name the chapter behind each.