Skip to content

Commit

Permalink
feat: added cryptogrpahy utlity and API
Browse files Browse the repository at this point in the history
  • Loading branch information
mattc41190 committed Jan 25, 2021
1 parent 56c49ee commit 7e64ce0
Show file tree
Hide file tree
Showing 15 changed files with 122 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ test_python:

.PHONY: test_single_python
test_single_python:
coverage run -m pytest -s utilities_for_me/utilities/_generate_random_string && coverage html
coverage run -m pytest -s utilities_for_me/utilities/_encrypt_decrypt && coverage html

.PHONY: check_python
check_python: typecheck_python format_python test_python
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ make deploy
- Date & Time Calculator
- Number Calculator
- Code Case Transformer ✅
- Random String Generator 🧗‍♂️
- Random String Generator
- Fake Data Creator
- Data Hashing
- Data Encryption
Expand Down
12 changes: 12 additions & 0 deletions examples/encrypt_decrypt/encrypt_decrypt.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
echo -----
curl --header "Content-Type: application/json" \
--request POST \
--data '{"message": "hello"}' \
http://localhost:5050/api/v1/encrypt-decrypt/encrypt

echo -----
echo "Use results from previous request! Expect to fail otherwise!"
curl --header "Content-Type: application/json" \
--request POST \
--data '{"key": "0ZeheiiSjKcKFCriQlvGkogDPCVD52xH2UXwZRzQJYA=", "encrypted_message": "gAAAAABgDhzULt1vg5lnn_Pu-G9mqgnQtwMY_dW3ZSzLtQ_vp0KMKU3hAj9-7We9F0e3SSkRPI1m6Nhvbmex6XQBOMk8bwthQQ=="}' \
http://localhost:5050/api/v1/encrypt-decrypt/decrypt
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ aniso8601==8.1.0
appdirs==1.4.4
attrs==20.3.0
black==20.8b1
cffi==1.14.4
click==7.1.2
coverage==5.3.1
cryptography==3.3.1
Flask==1.1.2
gunicorn==20.0.4
importlib-metadata==3.3.0
Expand All @@ -18,12 +20,14 @@ packaging==20.8
pathspec==0.8.1
pluggy==0.13.1
py==1.10.0
pycparser==2.20
pyparsing==2.4.7
pyrsistent==0.17.3
pytest==6.2.1
pytz==2020.5
regex==2020.11.13
six==1.15.0
termcolor==1.1.0
toml==0.10.2
typed-ast==1.4.1
typing-extensions==3.7.4.3
Expand Down
Empty file.
49 changes: 49 additions & 0 deletions utilities_for_me/utilities/_encrypt_decrypt/encrypt_decrypt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from typing import Dict

from cryptography.fernet import Fernet

KEY_LENGTH = 32
SUCCESS = "success"

UTF_8 = "utf8"


def generate_key() -> bytes:
return Fernet.generate_key()


def check_key(key: str) -> str:
if not isinstance(key, str):
return "key was not a string"
return SUCCESS


def encrypt(message: str) -> Dict[str, str]:
key = generate_key()
endcoded_message = message.encode()

f = Fernet(key)
encrypted_message = f.encrypt(endcoded_message)

result = {
"key": str(key, UTF_8),
"encrypted_message": str(encrypted_message, UTF_8),
}

return result


def decrypt(key: str, encrypted_message: str) -> str:
result = check_key(key)
if result != SUCCESS:
return result

try:
b_key = bytes(key, UTF_8)
b_encrypted_message = bytes(encrypted_message, UTF_8)
f = Fernet(b_key)
decrypted_message = f.decrypt(b_encrypted_message)
return str(decrypted_message, UTF_8)
except ValueError as e:
print(e)
return f"key or message invalid: {e}"
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from . import encrypt_decrypt


def test_encrypt_returns_key_and_encrypted_message():
result = encrypt_decrypt.encrypt("hello")
assert len(result["key"])
assert len(result["encrypted_message"])


def test_decrypt_returns_decrypted_message():
encrypt_result = encrypt_decrypt.encrypt("hello")
k = encrypt_result["key"]
m = encrypt_result["encrypted_message"]
result = encrypt_decrypt.decrypt(k, m)
assert result == "hello"
Empty file.
9 changes: 9 additions & 0 deletions utilities_for_me/utilities/_hash_data/hash_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import hashlib

SHA_256 = "sha256"
UTF_8 = "utf8"


def hash(algorithm: str = SHA_256, data: str = ""):
if algorithm == SHA_256:
return hashlib.sha256(bytes(data, UTF_8)).hexdigest()
5 changes: 5 additions & 0 deletions utilities_for_me/utilities/_hash_data/test_hash_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from . import hash_data


def test_hash_data_hashed_messages_as_expected():
print(hash_data.hash("sha256", "hello"))
Empty file.
20 changes: 20 additions & 0 deletions utilities_for_me/web_app/blueprints/api/encrypt_decrypt/bp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from flask import Blueprint, request

from utilities_for_me.utilities._encrypt_decrypt.encrypt_decrypt import encrypt, decrypt

bp = Blueprint("encrypt-decrypt", __name__, url_prefix="/api/v1/encrypt-decrypt")


@bp.route("/encrypt", methods=["POST"])
def encrypt_handler():
message = request.get_json(silent=True).get("message", "")
data = encrypt(message)
return {"data": data}


@bp.route("/decrypt", methods=["POST"])
def decrypt_handler():
key = request.get_json(silent=True).get("key", "")
encrypted_message = request.get_json(silent=True).get("encrypted_message", "")
data = decrypt(key, encrypted_message)
return {"data": data}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@


@bp.route("", methods=["POST"])
def calculate_percent_of_handler():
def generate_random_string_handler():
acceptable_categories = [
CAPITAL_LETTERS_TITLE,
LOWERCASE_LETTERS_TITLE,
Expand Down
2 changes: 1 addition & 1 deletion utilities_for_me/web_app/client/react/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function Home () {
<li> <span> <Link to='/echo' className='text-info'>Echo</Link> &mdash; A collection of utilities associated with general text transformations 🗣</span></li>
<li> <span> <Link to='/prettify' className='text-info'>Prettify</Link> &mdash; A collection of utilities associated with making structured data easier on the eyes ✨</span></li>
<li> <span> <Link to='/case-transform' className='text-info'>Case Transform</Link> &mdash; A collection of utilities associated with switching one code casing with another 💻</span></li>
<li> <span> <Link to='/calculate-percent' className='text-info'>Calculate Percent</Link> &mdash; A collection of utilities associated with computing percents %</span></li>
<li> <span> <Link to='/calculate-percent' className='text-info'>Calculate Percent</Link> &mdash; A collection of utilities associated with computing percents 💯</span></li>
<li> <span> <Link to='/generate-random-string' className='text-info'>Generate Random String</Link> &mdash; A utility that will get you reasonably random strings if you ask it nicely. 🔮</span></li>
</ul>
</div>
Expand Down
4 changes: 4 additions & 0 deletions utilities_for_me/web_app/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ def create_app(test_config=None):
from .blueprints.api.case_transform import bp as case_transform_bp
from .blueprints.api.calculate_percent import bp as calculate_percent_bp
from .blueprints.api.generate_random_string import bp as generate_random_string_bp
from .blueprints.api.encrypt_decrypt import bp as encrypt_decrypt_bp


app.register_blueprint(app_bp.bp)
app.register_blueprint(echo_bp.bp)
app.register_blueprint(case_transform_bp.bp)
app.register_blueprint(calculate_percent_bp.bp)
app.register_blueprint(generate_random_string_bp.bp)
app.register_blueprint(encrypt_decrypt_bp.bp)


return app

0 comments on commit 7e64ce0

Please sign in to comment.