Sub topic 8
Layer 6: Presentation, encoding, encryption, and compression
This chapter assumes you know the OSI layers from earlier chapters and how encapsulation works. You should also be comfortable reading short Python snippets and running commands in a terminal. The Session layer (Layer 5) sits below this layer, and the Application layer (Layer 7) sits above it.
What the Presentation layer is for
Layer 6 answers one question: do the two ends agree on what the bytes mean? Lower layers move bytes without caring what they represent. Layer 7 protocols such as HTTP or SMTP define messages and conversations. Layer 6 sits between them and covers three jobs:
- Encoding and data representation. This means character sets, number formats, byte order, and serialization formats.
- Encryption. This hides the content from anyone on the path.
- Compression. This reduces the number of bytes sent.
In the formal OSI definition, the Presentation layer translates between the application's own data structures and a common transfer syntax that both ends understand. The sender converts to that shared form and the receiver converts back.
Where Layer 6 lives in practice
Real software rarely has a component called "the Presentation layer". The TCP/IP model folds Layers 5 to 7 into one Application layer, so these functions are usually split between libraries and the application protocol itself.
| Function | Typical implementation | Where it appears in code |
|---|---|---|
| Character encoding | UTF-8, UTF-16, ASCII, Latin-1 | `str.encode()`, HTTP `Content-Type: text/html; charset=utf-8` |
| Serialization | JSON, XML, Protocol Buffers, ASN.1, CBOR | `json.dumps()`, generated protobuf classes |
| Byte order | Network byte order (big-endian) | `struct.pack("!I", n)`, `htonl()` |
| Encryption | TLS | `ssl` module, OpenSSL, browser TLS stack |
| Compression | gzip, Brotli, zstd, deflate | `Content-Encoding: gzip`, `gzip.compress()` |
Because these jobs are scattered, treat Layer 6 as a way of sorting concerns. When someone says "that's a Presentation problem," they mean the bytes arrived but were interpreted wrongly, were unreadable, or were packed in a form the receiver did not expect.
Encoding: agreeing on what bytes mean
Text is the most common case. A character set maps characters to numbers, and an encoding maps those numbers to bytes. If the sender and receiver choose different encodings, the bytes arrive intact but the text comes out garbled.
text = "café"
print(text.encode("utf-8")) # b'caf\xc3\xa9'
print(text.encode("latin-1")) # b'caf\xe9'
print(text.encode("utf-16-be")) # b'\x00c\x00a\x00f\x00\xe9'
# Receiver guesses the wrong encoding: the bytes are fine, the meaning is wrong.
wire_bytes = text.encode("utf-8")
print(wire_bytes.decode("latin-1")) # caféThe last line is a classic symptom called mojibake. UTF-8 stores é as two bytes (c3 a9), and Latin-1 reads each byte as a separate character. No packet was lost or corrupted. Both ends simply disagreed about the representation.
Byte order
Integers have the same problem. A 32-bit number occupies four bytes, and machines differ on which byte comes first. Internet protocols use network byte order, which is big-endian (most significant byte first).
import struct
n = 1
print(struct.pack("!I", n)) # b'\x00\x00\x00\x01' network order (big-endian)
print(struct.pack("<I", n)) # b'\x01\x00\x00\x00' little-endian
print(struct.pack(">I", n) == struct.pack("!I", n)) # TrueThe Ethernet example in the Layer 2 chapter used "!6s6sH" for the same reason. The ! tells struct to read multi-byte fields in network order. If you parse a binary protocol with the wrong byte order, an EtherType of 0x0806 would come out as 0x0608.
Serialization formats
Applications hold data in memory as objects, lists, and dictionaries, and those structures cannot be sent directly. Serialization converts them to a byte sequence, and deserialization rebuilds them. Common choices trade off readability against size and speed:
- JSON is text, human-readable, and supported everywhere. It is larger than binary formats and has no native type for binary data or for integers beyond what the parser supports exactly.
- XML is text and verbose. It supports schemas and namespaces, and it is still common in enterprise and telecom systems.
- Protocol Buffers and CBOR are binary and compact. They are faster to parse but are not readable without tooling. Protocol Buffers needs a schema shared in advance.
- ASN.1 is the format the OSI Presentation layer was originally designed around. You still meet it in X.509 certificates, LDAP, and SNMP.
The choice of serialization format is a Layer 6 decision even though your application code makes it.
Compression: fewer bytes, more CPU
Compression finds redundancy in the data and encodes it more compactly. It is lossless when the receiver can recover the original exactly, which is required for text, code, and JSON. It is lossy for media such as JPEG or MP3, where some detail is discarded permanently.
import gzip
import json
records = [{"id": i, "status": "ok", "region": "eu-west-1"} for i in range(200)]
payload = json.dumps(records).encode("utf-8")
packed = gzip.compress(payload)
print("original :", len(payload), "bytes")
print("compressed:", len(packed), "bytes")
assert gzip.decompress(packed) == payload # lossless round tripRepetitive data such as JSON with repeated keys compresses very well, so the compressed size is a small fraction of the original. Data that is already compressed or random, such as JPEG files, ZIP archives, or encrypted bytes, barely shrinks. Trying to compress it wastes CPU and can make it slightly larger.
In HTTP, the client advertises what it can decode with Accept-Encoding: gzip, br. The server replies with Content-Encoding: gzip if it applied compression. That negotiation is an application-layer header, while the work itself is a Presentation function.
Encryption: keeping content private
Encryption turns readable data (plaintext) into unreadable data (ciphertext) using a key. In practice this layer is almost always TLS (Transport Layer Security). TLS provides three properties:
- Confidentiality. Eavesdroppers on the path see only ciphertext.
- Integrity. Tampering with the data is detected.
- Authentication. The client verifies the server's identity through its certificate, and optionally the reverse.
TLS is the standard example of a protocol that does not fit the OSI model cleanly. It runs on top of TCP (Layer 4) and below HTTP (Layer 7), which is why textbooks place it at Layer 6. It also performs a handshake and manages session state, which resembles Layer 5. This is a good reason to treat the layers as a teaching tool and not as a strict classification.
import socket
import ssl
context = ssl.create_default_context() # verifies certificates and hostnames
with socket.create_connection(("example.com", 443), timeout=5) as raw:
with context.wrap_socket(raw, server_hostname="example.com") as tls:
print(tls.version()) # for example: TLSv1.3
print(tls.cipher()[0]) # negotiated cipher suite namewrap_socket performs the handshake on top of the existing TCP connection. After it returns, anything you send is encrypted and anything you receive is decrypted. The code above tls (HTTP, for example) never sees the ciphertext.
Order of operations: compress, then encrypt
When a pipeline does both, compression must come first. Encrypted data looks random, so compressing it afterward gains nothing. The receiver reverses the steps in the opposite order, decrypting first and then decompressing.
Common errors and how to recognize them
Most Presentation problems share one trait: the connection works and bytes flow, but the content is wrong.
- Garbled characters (
é,?, or�). The sender and receiver use different encodings. Check thecharsetinContent-Type, the file encoding, and the database or terminal encoding. UnicodeDecodeErrororinvalid start byte. The bytes are not valid in the encoding you assumed. They may be binary, compressed, or encrypted data being decoded as text.- Binary garbage where JSON was expected. The response is probably compressed or encrypted. Check
Content-Encoding. For example,curlshows raw compressed bytes unless you pass--compressed. - Numbers that are wildly wrong. Byte order mismatch or a wrong field width. A value of 1 read as 16,777,216 (
0x01000000) is the usual sign of swapped order. - TLS handshake failure. The two ends share no TLS version or cipher suite, the certificate is untrusted or expired, or the hostname does not match. Fix the certificate or protocol configuration, not the network path.
- Unexpectedly slow transfers with high CPU. Compression may be applied to data that is already compressed, or at a level too high for the throughput needed.
You can check what the server did from a terminal:
curl -sI -H "Accept-Encoding: gzip" https://example.com | grep -i -E "content-(type|encoding)"
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | grep -E "Protocol|Cipher"The first command shows the declared character set and compression. The second shows the TLS version and cipher that were negotiated.
Presentation versus its neighbors
Telling Layer 6 apart from Layer 5 and Layer 7 is a frequent exam and design question.
- Layer 7 defines what messages mean to the application:
GET,POST,RCPT TO. Layer 6 defines how the content of those messages is represented and protected. - Layer 5 manages the dialogue, such as opening, checkpointing, and closing a session. Layer 6 does not manage conversation state. It transforms the data inside one.
- Layer 4 delivers bytes reliably or unreliably between ports. It does not know whether those bytes are text, compressed, or encrypted.
Exercise
A client receives an HTTP response with status 200, but the body prints as unreadable binary characters. The response header contains Content-Encoding: gzip. Which layer's function was not undone, and what is the fix?
Show answer
The Presentation layer's compression step was not reversed. The server compressed the body, and the client treated the bytes as plain text. The fix is to decompress the body before decoding it, for example with gzip.decompress() in Python or curl --compressed. Note that the network was not at fault. The bytes arrived intact.
Exercise
A service sends the text "naïve" encoded as UTF-8, and the receiver displays "naïve". Name the cause and one way to prevent it.
Show answer
The receiver decoded UTF-8 bytes as Latin-1 (or a similar single-byte encoding). The character ï is two bytes in UTF-8 (c3 af), and each byte was shown as its own character. To prevent it, declare the encoding explicitly (for example Content-Type: text/plain; charset=utf-8) and make both ends decode with that encoding.
Exercise
Why should data be compressed before it is encrypted, and not the other way round?
Show answer
Good encryption output is statistically indistinguishable from random data, which has no redundancy for a compressor to remove. Compressing after encryption saves almost nothing. The receiver must also reverse the order: decrypt first, then decompress.