Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7d0e36b

Browse files
author
Justin
committed
Python Encrypt Example
1 parent 89bff04 commit 7d0e36b

File tree

13 files changed

+336
-1
lines changed

13 files changed

+336
-1
lines changed

‎HelloWorld.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# Store input numbers
21
print('Welcome to my first Hello World Program')
32
print('When you are ready to exit, enter an empty name')
43

‎HelloWorldSorted4.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import os.path
2+
#import our custom module (menuModule.py)
3+
import menuModule
4+
5+
filename = input('Enter a filename: ')
6+
7+
if os.path.exists(filename):
8+
with open(filename) as f:
9+
nameList = f.readlines()
10+
else:
11+
nameList = []
12+
13+
print('When you are ready to exit, enter an empty name')
14+
while True:
15+
userInput = menuModule.Menu()
16+
#If return from function is 1
17+
if userInput == '1':
18+
name = input('Enter name: ')
19+
nameList.append(name + '\n')
20+
print(name + " added")
21+
#else if return from function is q
22+
elif userInput == 'q':
23+
save = True
24+
break
25+
#else if return from function is x
26+
elif userInput == 'x':
27+
save = False
28+
break
29+
30+
# Only save if the user quit with 'q' not 'x'
31+
if save:
32+
nameList.sort()
33+
with open(filename, 'w', encoding='utf-8') as f:
34+
f.writelines(nameList)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Not a working encrypt function
2+
# just for the purpose of example
3+
def encryptFunc():
4+
print("ENCRYPTING")
5+
6+
# Example of a dictionary with a string and a function
7+
menuItem = {
8+
"name": "(1) encrypt",
9+
"func": encryptFunc
10+
}
11+
12+
# How we can access the name prop of our dictionary
13+
print(menuItem["name"])
14+
userInput = input(": ")
15+
16+
if userInput == '1':
17+
# We can even run the func that's in our dictionary
18+
menuItem["func"]()
19+
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
def encryptFunc():
2+
print("ENCRYPTING")
3+
4+
def decryptFunc():
5+
print("DECRYPTING")
6+
7+
menuItem1 = {
8+
"name": "(1) encrypt",
9+
"func": encryptFunc
10+
}
11+
12+
menuItem2 = {
13+
"name": "(2) decrypt",
14+
"func": decryptFunc
15+
}
16+
17+
menuItem3 = {
18+
"name": "(x) Exit"
19+
}
20+
21+
# Lists within lists
22+
menuData = {
23+
'1': menuItem1,
24+
'2': menuItem2,
25+
'x': { 'name': 'Exit'}
26+
}
27+
28+
for menuNameNum, menuItem in menuData.items():
29+
print(menuNameNum + " - " + menuItem["name"])
30+
31+
print( len(menuData))
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
NAME = 'name'
2+
FUNC = 'func'
3+
4+
def encryptFunc():
5+
print('ENCRYPTING')
6+
7+
def decryptFunc():
8+
print('DECRYPTING')
9+
10+
menuItem1 = {
11+
'name': '(1) encrypt',
12+
'func': encryptFunc
13+
}
14+
15+
menuItem2 = {
16+
'name': '(2) decrypt',
17+
'func': decryptFunc
18+
}
19+
20+
menuItem3 = {
21+
'name': '(x) Exit'
22+
}
23+
24+
# Lists within lists
25+
menuData = {
26+
'1': menuItem1,
27+
'2': menuItem2,
28+
'x': { 'name': 'Exit'}
29+
}
30+
31+
for menuNameNum, menuItem in menuData.items():
32+
print(menuNameNum + ' - ' + menuItem['name'])

‎PythonEncrypter/02/FileToEncrypt.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

‎PythonEncrypter/02/encryptExample.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Import the library we install in step 1
2+
import cryptography
3+
import base64
4+
import os
5+
from cryptography.hazmat.backends import default_backend
6+
from cryptography.hazmat.primitives import hashes
7+
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
8+
from cryptography.fernet import Fernet
9+
10+
# Password we'll supply to the method eventually
11+
password_provided = "password"
12+
# Turn password into a bit array
13+
password = password_provided.encode()
14+
15+
# Setup the KDF with a salt, which will be used to
16+
# create a key from the password
17+
salt = b'SOME_RANDOM_SALT'
18+
kdf = PBKDF2HMAC(
19+
algorithm=hashes.SHA512(),
20+
length=32,
21+
salt=salt,
22+
iterations=100000,
23+
backend=default_backend()
24+
)
25+
26+
# Create the key
27+
key = base64.urlsafe_b64encode(kdf.derive(password))
28+
# Start fernet (specific implementation of AES-128)
29+
fernet = Fernet(key)
30+
31+
# *** Show Encrypting a File ***
32+
33+
# Open the file as a bit array
34+
print('Opening file: FileToEncypt.txt')
35+
with open('FileToEncrypt.txt', 'rb') as f:
36+
data = f.read()
37+
38+
# Encrypt data
39+
print('Encrypting')
40+
encryptedData = fernet.encrypt(data)
41+
42+
# Save to output
43+
print('Saving encrypted: EncryptedFile.txt')
44+
with open('EncryptedFile.txt', 'wb') as f:
45+
f.write(encryptedData)
46+
47+
# *** Show Decrypting a File ***
48+
49+
# Open file
50+
print('Opening encrypted file')
51+
with open('EncryptedFile.txt', 'rb') as f:
52+
encryptedFileData = f.read()
53+
54+
# Decrypt
55+
print('Decrypting file')
56+
decryptedFileData = fernet.decrypt(encryptedFileData)
57+
58+
# Save decrypted file
59+
print('Saving decrypted file data')
60+
with open('DecryptedFile.txt', 'wb') as f:
61+
f.write(decryptedFileData)
62+
63+
print("----")
64+
print("DONE")

‎PythonEncrypter/encrypter.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Import the library we install in step 1
2+
import cryptography
3+
import base64
4+
import os
5+
from cryptography.hazmat.backends import default_backend
6+
from cryptography.hazmat.primitives import hashes
7+
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
8+
from cryptography.fernet import Fernet
9+
10+
SALT = b'SOME_RANDOM_SALT'
11+
12+
def Encrypter(filename, password):
13+
password = password.encode()
14+
15+
kdf = PBKDF2HMAC(
16+
algorithm=hashes.SHA512(),
17+
length=32,
18+
salt=SALT,
19+
iterations=100000,
20+
backend=default_backend()
21+
)
22+
23+
key = base64.urlsafe_b64encode(kdf.derive(password))
24+
fernet = Fernet(key)
25+
26+
print('Opening file: ' + filename)
27+
with open(filename, 'rb') as f:
28+
data = f.read()
29+
30+
print('Encrypting...')
31+
encryptedData = fernet.encrypt(data)
32+
33+
print('Saving encrypted: ' + filename + '.enc')
34+
with open(filename + '.enc', 'wb') as f:
35+
f.write(encryptedData)
36+
37+
print("----")
38+
print("DONE")
39+
40+
def Decrypter(filename, password):
41+
password = password.encode()
42+
43+
kdf = PBKDF2HMAC(
44+
algorithm=hashes.SHA512(),
45+
length=32,
46+
salt=SALT,
47+
iterations=100000,
48+
backend=default_backend()
49+
)
50+
51+
key = base64.urlsafe_b64encode(kdf.derive(password))
52+
fernet = Fernet(key)
53+
54+
# Open file
55+
print('Opening encrypted file: ' + filename)
56+
with open(filename, 'rb') as f:
57+
encryptedFileData = f.read()
58+
59+
# Decrypt
60+
print('Decrypting file...')
61+
decryptedFileData = fernet.decrypt(encryptedFileData)
62+
63+
# Let's remove the .enc that we added when encrypting
64+
decryptedFilename = filename.replace('.enc','')
65+
# Let's add dec prefix just in case the old unecrypted file
66+
# is still there.
67+
decryptedFilename = 'dec_' + decryptedFilename
68+
69+
print('Saving decrypted file data: ' + decryptedFilename)
70+
with open(decryptedFilename, 'wb') as f:
71+
f.write(decryptedFileData)
72+
73+
print("----")
74+
print("DONE")

‎PythonEncrypter/main.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from menu import Menu
2+
from encrypter import Encrypter, Decrypter
3+
4+
def EncryptFunc():
5+
print()
6+
filename = input("Filename: ")
7+
password = input("Password: ")
8+
Encrypter(filename, password)
9+
10+
def DecryptFunc():
11+
print()
12+
filename = input("Filename: ")
13+
password = input("Password: ")
14+
Decrypter(filename, password)
15+
16+
mainMenu = Menu('Python Encrypter')
17+
mainMenu.addMenuItem('Encrypt file', EncryptFunc)
18+
mainMenu.addMenuItem('Decrypt file', DecryptFunc)
19+
mainMenu.run()

‎PythonEncrypter/menu.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# It's bad to use string literals everywhere so we
2+
# willd define some constants to use instead
3+
NAME = 'name'
4+
FUNC = 'func'
5+
6+
class Menu:
7+
# Class constructor in python
8+
def __init__(self, title):
9+
# title of our menu
10+
self.title = title
11+
# Our dictionary of dictionaries
12+
self.menuData = {}
13+
# Total number of items in menu
14+
self.itemsInMenu = 0
15+
16+
def addMenuItem(self, name, func):
17+
# Menu number is the length of our menuData
18+
# dictionary plus one
19+
menuNumber = len(self.menuData) + 1
20+
self.menuData[str(menuNumber)] = { NAME: name, FUNC: func }
21+
22+
def run(self):
23+
while True:
24+
print ()
25+
print ()
26+
print ("*** " + self.title + " ***")
27+
print ()
28+
for menuNum, menuItem in self.menuData.items():
29+
print(menuNum + ' - ' + menuItem[NAME])
30+
print("x - exit")
31+
print()
32+
userInput = input(": ")
33+
34+
if userInput == 'x':
35+
break
36+
37+
#Select the right item from our menu or "false"
38+
#if it's not there
39+
selected = self.menuData.get(userInput, False)
40+
41+
# User selected item that wasn't in our list
42+
if not selected:
43+
input("INVALID INPUT -- press enter to continue")
44+
else:
45+
#Run the function that was selected
46+
selected[FUNC]()
47+
input("Complete -- press enter to continue")

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /