Class 4 Lab 7 ‐ Encoding & Decoding the Secret - Justin-Boyd/Python-Class GitHub Wiki
Step 1
- Create a new Python file in PyCharm by right-clicking the project you created and selecting New > Python File.
Step 2
- Import the Base64 module.
import base64
Step 3
- Ask the user to provide a secret, and assign it to a variable.
secret = input("Please enter a secret: ")
Step 4
- Encode the secret using b64encode() and then convert the Byte data type returned by b64encode() to UTF-8 encoding. Save the output to a new variable.
- Note: The aim is to encode the base64 secret, but the secret will also need to be encoded to UTF-8 format to obtain a readable message required by the base64 module.
encoded = base64.b64encode(secret.encode("utf-8"))
Step 5
- Decode the secret using b64decode(), and save the output to a new variable.
decoded = base64.b64decode(encoded)
Step 6
- Print the encoded secret.
- Note that the output is “gibberish” (unreadable), which is what we want.
print("The encoded string is ", encoded)
Step 7
- Print the decoded secret.
- Note: The output will show a b’{input_string}’. Suppose the string you entered was ‘p@wn3d’ in Step 2. You would then see an output of b’p@wn3d’. The string inside the single quotes after the “b” is the decoded string.
print("The decoded string is ", decoded)
Final Code
import base64
secret = input("Please enter a secret: ")
encoded = base64.b64encode(secret.encode("utf-8"))
decoded = base64.b64decode(encoded)
print("The encoded string is ", encoded)
print("The decoded string is ", decoded)