Debian Codegraph @

Doc/src/examples.rst

raw
1 Examples
2 ========
3
4 Encrypt data with AES
5 ~~~~~~~~~~~~~~~~~~~~~
6
7 The following code generates a new AES-128 key and encrypts a piece of data into a file.
8 We use the :ref:`CTR mode <ctr_mode>` (which is a :ref:`classic mode of operation <classic_cipher_modes>`,
9 simple but not erecommended anymore).
10
11 With CTR alone, the receiver is not able to detect if the *ciphertext* (i.e., the encrypted
12 data) was modified while in transit. To address that risk, we also attach
13 a MAC authentication tag (HMAC with SHA256), made with a second key.
14
15 .. code-block:: python
16
17 from Crypto.Cipher import AES
18 from Crypto.Hash import HMAC, SHA256
19 from Crypto.Random import get_random_bytes
20
21 data = 'secret data to transmit'.encode()
22
23 aes_key = get_random_bytes(16)
24 hmac_key = get_random_bytes(16)
25
26 cipher = AES.new(aes_key, AES.MODE_CTR)
27 ciphertext = cipher.encrypt(data)
28
29 hmac = HMAC.new(hmac_key, digestmod=SHA256)
30 tag = hmac.update(cipher.nonce + ciphertext).digest()
31
32 for open("encrypted.bin", "wb") as f:
33 f.write(tag)
34 f.write(nonce)
35 f.write(ciphertext)
36
37 # Share securely aes_key and hmac_key with the receiver
38 # encrypted.bin can be sent over an unsecure channel
39
40 At the other end, the receiver can securely load the piece of data back (if they know the two keys!).
41 Note that the code generates a ``ValueError`` exception when tampering is detected.
42
43 .. code-block:: python
44
45 import sys
46 from Crypto.Cipher import AES
47 from Crypto.Hash import HMAC, SHA256
48
49 # Somehow, the receiver securely get aes_key and hmac_key
50 # encrypted.bin can be sent over an unsecure channel
51
52 with open("encrypted.bin", "rb") as f:
53 tag = f.read(32)
54 nonce = f.read(8)
55 ciphertext = f.read()
56
57 try:
58 hmac = HMAC.new(hmac_key, digestmod=SHA256)
59 tag = hmac.update(nonce + ciphertext).verify(tag)
60 except ValueError:
61 print("The message was modified!")
62 sys.exit(1)
63
64 cipher = AES.new(aes_key, AES.MODE_CTR, nonce=nonce)
65 message = cipher.decrypt(ciphertext)
66 print("Message:", message.decode())
67
68 Encrypt and authenticate data in one step
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70
71 The code in the previous section contains three subtle but important design decisions:
72 the *nonce* of the cipher is authenticated, the authentication is performed
73 after encryption, and encryption and authentication use two uncorrelated keys.
74 It is not easy to securely combine cryptographic primitives,
75 so more modern cryptographic cipher
76 modes have been created such as, the :ref:`OCB mode <ocb_mode>`
77 (see also other :ref:`authenticated encryption modes <modern_cipher_modes>`
78 like :ref:`EAX <eax_mode>`, :ref:`GCM <gcm_mode>`, :ref:`CCM <ccm_mode>`, :ref:`SIV <siv_mode>`).
79
80 .. code-block:: python
81
82 from Crypto.Cipher import AES
83 from Crypto.Random import get_random_bytes
84
85 data = 'secret data to transmit'.encode()
86
87 aes_key = get_random_bytes(16)
88
89 cipher = AES.new(aes_key, AES.MODE_OCB)
90 ciphertext, tag = cipher.encrypt_and_digest(data)
91 assert len(cipher.nonce) == 15
92
93 with open("encrypted.bin", "wb") as f:
94 f.write(tag)
95 f.write(cipher.nonce)
96 f.write(ciphertext)
97
98 # Share securely aes_key and hmac_key with the receiver
99 # encrypted.bin can be sent over an unsecure channel
100
101 Decryption is also simpler:
102
103 .. code-block:: python
104
105 import sys
106 from Crypto.Cipher import AES
107
108 # Somehow, the receiver securely get aes_key and hmac_key
109 # encrypted.bin can be sent over an unsecure channel
110
111 with open("encrypted.bin", "rb") as f:
112 tag = f.read(16)
113 nonce = f.read(15)
114 ciphertext = f.read()
115
116 cipher = AES.new(aes_key, AES.MODE_OCB, nonce=nonce)
117 try:
118 message = cipher.decrypt_and_verify(ciphertext, tag)
119 except ValueError:
120 print("The message was modified!")
121 sys.exit(1)
122
123 print("Message:", message.decode())
124
125 Generate an RSA key
126 ~~~~~~~~~~~~~~~~~~~
127
128 The following code generates a new RSA key pair (secret) and saves it into a file, protected by a password.
129 We use the :ref:`scrypt <scrypt_func>` key derivation function to thwart dictionary attacks.
130 At the end, the code prints our the RSA public key in ASCII/PEM format:
131
132 .. code-block:: python
133
134 from Crypto.PublicKey import RSA
135
136 secret_code = "Unguessable"
137 key = RSA.generate(2048)
138 encrypted_key = key.export_key(passphrase=secret_code, pkcs=8,
139 protection="scryptAndAES128-CBC",
140 prot_params={'iteration_count':131072})
141
142 with open("rsa_key.bin", "wb") as f:
143 f.write(encrypted_key)
144
145 print(key.publickey().export_key())
146
147 The following code reads the private RSA key back in, and then prints again the public key:
148
149 .. code-block:: python
150
151 from Crypto.PublicKey import RSA
152
153 secret_code = "Unguessable"
154 encoded_key = open("rsa_key.bin", "rb").read()
155 key = RSA.import_key(encoded_key, passphrase=secret_code)
156
157 print(key.publickey().export_key())
158
159
160 Generate public key and private key
161 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
162
163 The following code generates public key stored in ``receiver.pem`` and private key stored in ``private.pem``. These files will be used in the examples below. Every time, it generates different public key and private key pair.
164
165 .. code-block:: python
166
167 from Crypto.PublicKey import RSA
168
169 key = RSA.generate(2048)
170 private_key = key.export_key()
171 with open("private.pem", "wb") as f:
172 f.write(private_key)
173
174 public_key = key.publickey().export_key()
175 with open("receiver.pem", "wb") as f:
176 f.write(public_key)
177
178 Encrypt data with RSA
179 ~~~~~~~~~~~~~~~~~~~~~
180
181 The following code encrypts a piece of data for a receiver we have the RSA public key of.
182 The RSA public key is stored in a file called ``receiver.pem``.
183
184 Since we want to be able to encrypt an arbitrary amount of data, we use a hybrid encryption scheme.
185 We use RSA with PKCS#1 :ref:`OAEP <rsa_oaep>` for asymmetric encryption of an AES session key.
186 The session key can then be used to encrypt all the actual data.
187
188 As in the first example, we use the EAX mode to allow detection of unauthorized modifications.
189
190 .. code-block:: python
191
192 from Crypto.PublicKey import RSA
193 from Crypto.Random import get_random_bytes
194 from Crypto.Cipher import AES, PKCS1_OAEP
195
196 data = "I met aliens in UFO. Here is the map.".encode("utf-8")
197
198 recipient_key = RSA.import_key(open("receiver.pem").read())
199 session_key = get_random_bytes(16)
200
201 # Encrypt the session key with the public RSA key
202
203 cipher_rsa = PKCS1_OAEP.new(recipient_key)
204 enc_session_key = cipher_rsa.encrypt(session_key)
205
206 # Encrypt the data with the AES session key
207
208 cipher_aes = AES.new(session_key, AES.MODE_EAX)
209 ciphertext, tag = cipher_aes.encrypt_and_digest(data)
210
211 with open("encrypted_data.bin", "wb") as f:
212 f.write(enc_session_key)
213 f.write(cipher_aes.nonce)
214 f.write(tag)
215 f.write(ciphertext)
216
217 The receiver has the private RSA key. They will use it to decrypt the session key
218 first, and with that the rest of the file:
219
220 .. code-block:: python
221
222 from Crypto.PublicKey import RSA
223 from Crypto.Cipher import AES, PKCS1_OAEP
224
225 private_key = RSA.import_key(open("private.pem").read())
226
227 with open("encrypted_data.bin", "rb") as f:
228 enc_session_key = f.read(private_key.size_in_bytes())
229 nonce = f.read(16)
230 tag = f.read(16)
231 ciphertext = f.read()
232
233 # Decrypt the session key with the private RSA key
234 cipher_rsa = PKCS1_OAEP.new(private_key)
235 session_key = cipher_rsa.decrypt(enc_session_key)
236
237 # Decrypt the data with the AES session key
238 cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
239 data = cipher_aes.decrypt_and_verify(ciphertext, tag)
240 print(data.decode("utf-8"))