One shared key
Encryption scrambles data so only someone with the right key can read it. In symmetric encryption the same secret key does both jobs: it locks (encrypts) and unlocks (decrypts). Alice and Bob each hold a copy of one key.
Lock it in Python
Alice wants to send Bob "pay 50". Readable data is called plaintext. The b in b"pay 50" makes it bytes, because ciphers work on bytes, not letters. Line 1 stores those six bytes in msg.
os.urandom(32) asks the operating system for 32 random bytes: a 256-bit key. AES, the standard cipher, accepts 128, 192 or 256-bit keys. The method is public; only the key is secret. AESGCM(key) builds a cipher that uses it.
Each message also needs a nonce, a number used once: 12 random bytes (96 bits), the size NIST recommends for this mode. The nonce is not secret and travels with the message, but it must never repeat under the same key.
encrypt() runs AES in GCM mode. AES scrambles the bytes with the key; GCM adds a 16-byte tag, a check value only the key can make. So ct is the ciphertext: 6 scrambled bytes plus the tag, 22 bytes in all.
Send and unlock
Alice sends the nonce and ct over the network. Eve, an eavesdropper, can copy everything that passes. Without the key the 22 bytes look random, so the message stays confidential.
Bob uses his copy of the same key and the nonce. decrypt() first checks the tag, then reverses the scrambling. Out comes b"pay 50": the original plaintext.
Suppose Eve changes one byte of ct on the way, hoping to alter the amount. The tag no longer matches, so decrypt() raises InvalidTag and returns nothing. Authenticated encryption protects integrity as well as secrecy.
Mistakes and fixes
A common mistake is reusing a nonce with the same key, for example a fixed value in the code. In GCM that can leak plaintext and lets attackers forge tags. The fix: a fresh random nonce for every message, as line 4 does.
Anyone with the key can read and forge messages. Never write keys into code or a repository; keep them in a key manager, and use a vetted library, not a homemade cipher. One problem remains: how does Bob get the key safely?
What happens
;; step 1/10 · shared-key encryption plaintext + key → ciphertext decryption ciphertext + key → plaintext symmetric the SAME key does both Alice holds a copy of the key Bob holds a copy of the same key goal confidentiality (only key holders can read)
The example runs in one Python program so you can try it. In real life Alice and Bob run separate programs; Bob builds his own AESGCM(key) from his copy of the key. AESGCM comes from the widely used cryptography package (pip install cryptography), not the standard library. os.urandom is in the standard library and is meant for cryptographic use.