Encoding and hashing
Identity systems send, sign and compare bytes. Encodings write those bytes as text so they can travel safely, while hashes turn them into short digests that reveal even the smallest change.
Bytes and characters
A text message, a photo and a song all end up stored the same way: as a sequence of bytes. A byte is a small number from 0 to 255, and on its own it means nothing. Whether the bytes are pixels, sound or letters depends on how a program agrees to read them.
For text, that agreement is a character encoding, a
table that gives each character a number. A classic one, still at the
heart of the others, is ASCII, which covers 128 characters:
English letters, digits, punctuation and a few control characters such
as the newline. In ASCII, H is 72 and i is
105, one byte each. Today almost everything uses
UTF-8, which keeps every ASCII character as the same
single byte and writes every other character, from é to
Chinese characters and emoji, as two to four bytes.
You can see the difference by counting. printf '%s'
prints exactly the text that follows, and wc -c counts
the bytes it receives:
$ printf '%s' 'Hi' | wc -c
2
$ printf '%s' 'café' | wc -c
5
$ echo 'Hi' | wc -c
3
café has four characters but five bytes, because
é takes two in UTF-8. The last line shows something that
matters for the rest of this lesson: echo adds a newline
after its text, and that newline is a byte too. When the exact bytes
matter, as they do for everything below, use
printf '%s' instead of echo. On macOS,
wc pads the number with spaces, so the counts appear
further to the right.
Seeing bytes in hex
To look at bytes directly, people write them in
hexadecimal, or hex: counting in
sixteens, with the digits 0 to 9 followed by
a to f. Two hex digits cover exactly one
byte, from 00 for 0 to ff for 255, so
H, which is 72, is 48 in hex.
od, short for octal dump, prints the bytes it reads.
-An leaves out the position column it normally adds, and
-tx1 asks for hex, one byte at a time:
$ printf '%s' 'Hi' | od -An -tx1
48 69
$ echo 'Hi' | od -An -tx1
48 69 0a
$ printf '%s' 'café' | od -An -tx1
63 61 66 c3 a9
The spacing can differ a little between systems, but the bytes are the
same. The newline that echo added appears as
0a, and é is the two bytes
c3 a9. Hex is an encoding in its own right: a way to write
any bytes using only ordinary characters, at the cost of two
characters per byte.
Base64: bytes as text
Plenty of places can carry only text. An HTTPThe Hypertext Transfer Protocol, the rules browsers, apps, and servers use to send requests and responses on the web. header, a JSONA text format for structured information, written as named values inside curly braces. APIs, tokens, and discovery documents all use it. string or
an email body cannot safely hold arbitrary bytes, because some bytes
are invisible control characters and others are not valid text at
all. Base64, which
Keys, encryptionTransforming data so that only someone holding the right key can read it. It protects confidentiality and, unlike hashing, is designed to be reversed by the key holder., and signatures introduced, solves this by writing any bytes with 64 safe characters:
A to Z, a to z,
0 to 9, + and /.
It is more compact than hex, using four characters for every three
bytes.
It works by regrouping bits. Three bytes are 24 bits, which split into
four groups of 6 bits, and each 6-bit group is a number from 0 to 63
that picks one character. Hi is only two bytes,
48 69 in hex, which is 16 bits:
01001000 01101001. Split into groups of 6, with zero bits
added to fill the last, they become 010010 000110 100100:
the numbers 18, 6 and 36, which pick the characters S,
G and k. One = completes the
group of four characters, so Hi in base64 is
SGk=.
Bytes in hex
- Value
- 48 69
- Reads as
- Hi is only two bytes
- Hi and the newline
- 48 69 0a
Bits
- Value
- 01001000 01101001
- Reads as
- The same two bytes
- Hi and the newline
- 01001000 01101001 00001010
Split into groups of 6
- Value
- 010010 000110 100100
- Reads as
- The numbers 18, 6 and 36
- Hi and the newline
- 010010 000110 100100 001010
One character for each group
- Value
- SGk=
- Reads as
- S, G and k, then one =
- Hi and the newline
- SGkK
For Hi, zero bits are added to fill the last group. The padding tells a decoder how many real bytes the last group holds.
The = at the end is padding. Base64 always
writes complete groups of four characters, so when the last group of
bytes is short, it fills the gap with =: one when two bytes
were left over, two when only one byte was. The padding tells a decoder
how many real bytes the last group holds.
$ printf '%s' 'H' | base64
SA==
$ printf '%s' 'Hi' | base64
SGk=
$ printf '%s' 'Hi!' | base64
SGkh
$ echo 'Hi' | base64
SGkK
The last line encodes three bytes, H, i and
the newline, so it needs no padding but no longer matches
SGk=. Its bytes are 48 69 0a, which is 24
bits: 01001000 01101001 00001010. They split into four
full groups, 010010 000110 100100 001010: the numbers 18,
6, 36 and 10, which pick S, G, k
and K. base64 -d decodes, turning the
characters back into the original bytes:
$ printf '%s' 'SGk=' | base64 -d
Hi
For long input, base64 on Linux splits its output across
several lines, while macOS keeps it on one. When you need the
result as one exact line, use openssl base64 -A to encode
and openssl base64 -d -A to decode; -A means
"all on one line". It prints no newline at the end either, so your next
prompt may appear right after the result.
Anyone can decode base64. It changes how bytes are written, not who can read them, so it hides nothing. A password or tokenA piece of data issued by a trusted service that a client presents as a credential, for example to call an API or to report a sign-in. Some tokens carry readable claims; others are random strings that only the issuer can interpret. in base64 is as exposed as the plain text.
Base64url and percent-encoding
Three of the characters base64 uses already have jobs in a URL.
/ separates parts of a path, = separates a
query parameter's name from its value, and + is often read
as a space. Base64url is the same encoding with two
characters swapped, - instead of + and
_ instead of /, and usually without the
padding. The result can sit in a URL, a file name or a cookieA small value that a website asks the browser to store and send back with later matching requests. Cookies commonly carry a session identifier, so the site can recognize an ongoing sign-in without your password.
unchanged. Identity systems use it for exactly that reason: tokens and
the values exchanged during sign-in travel in URLs and headers, so they
are written in base64url.
Converting takes one more step after base64. tr translates
characters: tr '+/' '-_' turns each + into
- and each / into _, and
tr -d '=' deletes the padding.
Searching and shaping text
covers tr in more depth.
$ printf '%s' 'Ready? Go!' | openssl base64 -A
UmVhZHk/IEdvIQ==
$ printf '%s' 'Ready? Go!' | openssl base64 -A | tr '+/' '-_' | tr -d '='
UmVhZHk_IEdvIQ
Decoding runs the same steps backwards: swap the characters back, put
the padding back, then decode. The padding matters. Without it,
decoders either refuse the input or quietly lose the last bytes, and
openssl base64 -d -A may print nothing at all. Base64 text
is always a multiple of four characters long, so add =
until it is. ${#b64} is the length of the variable
b64, and the loop adds one = at a time while
that length is not a multiple of four:
b64=$(printf '%s' 'UmVhZHk_IEdvIQ' | tr '_-' '/+')
while [[ $(( ${#b64} % 4 )) -ne 0 ]]; do b64="$b64="; done
printf '%s' "$b64" | openssl base64 -d -AReady? Go!
Notice that the swap back is written tr '_-' '/+', with
the dash last. An argument that starts with a dash looks like an
option, so tr '-_' '+/' would confuse tr.
URLs have their own encoding for everything else, the
percent-encoding from
Clients, servers, and addresses.
Its two-character codes are hex: a character that is not allowed, or
that would be misread, is replaced by a % and the two hex
digits of each of its bytes. A space becomes %20,
+ becomes %2B, = becomes
%3D, and é, the two UTF-8 bytes
c3 a9, becomes %C3%A9. In form data a space
is often written as + instead of %20, which
is exactly why a real plus sign has to be encoded.
curl --data-urlencode does this for you. Given
name=value, it encodes the part after the first
= and sends it as form data in the request body. Adding
-G moves the same data into the URL's query string and
sends a GET request instead:
curl --data-urlencode 'q=1+1=2' https://api.example.com/search
curl -G --data-urlencode 'q=1+1=2' https://api.example.com/search
The first sends the body q=1%2B1%3D2, and the second
requests /search?q=1%2B1%3D2. Sent without the encoding,
the value would usually reach the server as 1 1=2, with
the plus read as a space.
Hashing with SHA-256
Encoding changes how bytes are written and can always be undone.
Hashing is different. A hash function
reads any amount of input, from one byte to a whole disk image, and
produces a short, fixed-size result called a digest,
or simply the hash. SHA-256, the hash identity systems
rely on most, always produces 32 bytes, usually shown as 64 hex digits.
openssl dgst -sha256 computes it:
$ printf '%s' 'hello' | openssl dgst -sha256
SHA2-256(stdin)= 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
$ printf '%s' 'Hello' | openssl dgst -sha256
SHA2-256(stdin)= 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
$ echo 'hello' | openssl dgst -sha256
SHA2-256(stdin)= 5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03
SHA2-256 is OpenSSL's name for SHA-256, and
stdin means the input came through the pipe. Given a file
name instead, such as openssl dgst -sha256 photo.jpg, it
shows the name. These three results show the properties that make
hashes useful:
- The same input always gives the same digest, on any computer, so two parties can compare digests instead of whole files.
-
A small change gives a completely different digest.
One capital letter, or the newline that
echoadds, was enough here. There is no "nearly the same" digest that hints at a nearly the same input. - It only works one way. Nothing turns a digest back into its input. The only way to find an input is to guess one, hash it and compare.
That last property is why a hash is not encryption. Encryption uses a key so that the right person can get the original back; a hash has no key and nothing to decrypt.
| Question | Encoding (hex, base64, base64url) | Hashing (SHA-256) |
|---|---|---|
| Can you get the input back? | Yes, by decoding | No |
| Output size | Grows with the input | Always 32 bytes |
| Uses a key? | No | No |
| Used for | Carrying bytes through text | Checking that bytes match a digest from a source you trust |
Encoding a digest
The 64 hex digits that openssl dgst prints are themselves
an encoding of the 32 digest bytes. Protocols often want those bytes in
base64url instead, because it is shorter and fits in a URL. The
-binary option makes openssl dgst print the
raw bytes rather than hex. Raw bytes look like garbage in a terminal,
so send them to another command instead:
$ printf '%s' 'hello' | openssl dgst -sha256 -binary | wc -c
32
$ printf '%s' 'hello' | openssl dgst -sha256 -binary | od -An -tx1
2c f2 4d ba 5f b0 a3 0e 26 e8 3b 2a c5 b9 e2 9e
1b 16 1e 5c 1f a7 42 5e 73 04 33 62 93 8b 98 24These are the same bytes as the hex digest above, written with spaces. Now encode them, first as base64, then as base64url:
$ printf '%s' 'hello' | openssl dgst -sha256 -binary | openssl base64 -A
LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=
$ printf '%s' 'hello' | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '='
LPJNul-wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ
The base64 form is 44 characters, ending in one =,
because 32 bytes leave two over after groups of three. The base64url
form is 43 characters, with the + swapped for
- and the padding gone. Hex, base64 and base64url here are
three ways of writing one digest; comparing a hex digest with a
base64url one character by character would wrongly say they differ.
Protocols that carry a digest in a URL use exactly this pipeline: hash the exact bytes, then write the 32 digest bytes in base64url. Hashing the text you can see instead of those bytes, or the base64url form of a value instead of the value it encodes, gives a digest that is just as well formed and completely different.
What a digest proves
Suppose Ava downloads a photo editor, and the publisher's site lists the file's SHA-256 digest beside the download link. She hashes her copy, and the two digests match. What has she learned? That her file has exactly the bytes the listed digest describes: nothing was damaged or changed between that digest and her disk. That property is called integrity.
She has not learned who made the file. Hashing needs no key, so anyone can compute a digest. Someone who can replace the file on the publisher's server can replace the listed digest at the same moment, and the two still match. A digest is therefore only as trustworthy as the place it came from. One that arrives by a separate route you already trust says far more than one sitting next to the download.
Knowing who produced something, and that they really did, is called authenticity, and it needs something that only the producer holds: a key. A keyed hash, called an HMAC, shows that the data came from someone who holds a shared secret. A digital signature shows that it came from the holder of a private keyThe half of a key pair that its owner keeps to themselves and uses to create signatures or decrypt data. Anyone who obtains it can act as its owner., and anyone with the matching public keyThe half of a key pair that can be shared freely. It checks signatures made with the matching private key and can encrypt data that only that private key can decrypt. can check it. Tokens are signed rather than merely hashed for exactly this reason. Secrets and key pairs and Digital signatures explain both.
Not every hash function still earns that trust. MD5 and SHA-1 give
shorter digests, 16 and 20 bytes, and both are broken: researchers can
build two different inputs with the same digest, called a
collision. MD5 collisions have been practical since
2004, and the first SHA-1 collision was published in 2017. A collision
lets someone get one file approved and then swap in another with the
same digest. Both functions survive in older systems, such as
certificateA signed statement that a public key belongs to a name, such as a website's hostname, for stated purposes and a limited period. A certificate authority signs it, so software that trusts the authority can connect the key to the name. thumbprints and signature algorithm names that end in
sha1, and newer systems replace them with their SHA-256
versions.
Passwords need a different kind of function altogether. SHA-256 is fast, so an attacker with a stolen password digest can guess billions of passwords a second. Password hashing functions such as Argon2id, scrypt, bcrypt and PBKDF2 are deliberately slow, and Argon2id and scrypt also need a lot of memory, so every guess costs real work. They mix in a salt, a random value stored beside each digest, so two people with the same password get different digests, and an attacker cannot reuse one table of precomputed guesses against everyone.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Decode a base64url message and send back its SHA-256 digestLook at bytes in hex, write and test your own b64url and b64url_decode functions, see percent-encoding on the wire, hash with SHA-256, then decode a message and send its digest in base64url.