Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: refactor code to meet pylint style guidelines. WIP #36

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 35 additions & 55 deletions encryptor/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
"""
Encryptor

https://github.com/rafaeelaudibert/Encryptor/
"""

import os

import sentry_sdk
Expand All @@ -17,8 +23,9 @@
if os.environ.get("SENTRY_DSN", None) or os.getenv("SENTRY_DSN"):
sentry_sdk.init(
dsn=os.environ.get("SENTRY_DSN", None) or os.getenv("SENTRY_DSN"),
release="encryptor@{}".format(os.environ.get("PACKAGE_VERSION", None)
or os.getenv("PACKAGE_VERSION"))
release="encryptor@{}".format(
os.environ.get("PACKAGE_VERSION", None) or os.getenv("PACKAGE_VERSION")
)
or "encryptor@no_version",
integrations=[FlaskIntegration()],
)
Expand Down Expand Up @@ -48,113 +55,86 @@ def create_app(test_config=None):
pass

# ROUTES
# pylint: disable=unused-variable
chtnnh marked this conversation as resolved.
Show resolved Hide resolved
@app.route("/api/ceasar/encrypt/<text>")
def ceasar_encrypt(text):
offset = request.args.get("offset", Ceasar.DEFAULT_OFFSET)

return jsonify({
"status": 200,
"content": Ceasar.encrypt(text, offset)
})
return jsonify({"status": 200, "content": Ceasar.encrypt(text, offset)})

@app.route("/api/ceasar/decrypt/<text>")
def ceasar_decrypt(text):
offset = request.args.get("offset", Ceasar.DEFAULT_OFFSET)

return jsonify({
"status": 200,
"content": Ceasar.decrypt(text, offset)
})

return jsonify({"status": 200, "content": Ceasar.decrypt(text, offset)})

@app.route("/api/vigenere/encrypt/<text>")
def vigenere_encrypt(text):
tabula_recta = request.args.get("tabula_recta", Vigenere.ALPHABET)
key = request.args.get("key", Vigenere.KEY)

return jsonify({
"status": 200,
"content": Vigenere.encrypt(text, key, tabula_recta)
})
return jsonify(
{"status": 200, "content": Vigenere.encrypt(text, key, tabula_recta)}
)

@app.route("/api/vigenere/decrypt/<text>")
def vigenere_decrypt(text):
tabula_recta = request.args.get("tabula_recta", Vigenere.ALPHABET)
key = request.args.get("key", Vigenere.KEY)

return jsonify({
"status": 200,
"content": Vigenere.decrypt(text, key, tabula_recta)
})
return jsonify(
{"status": 200, "content": Vigenere.decrypt(text, key, tabula_recta)}
)

@app.route("/api/railfence/encrypt/<text>")
def railfence_encrypt(text):
rail_height = request.args.get("rail_height", RailFence.DEFAULT_RAILS)

return jsonify({
"status": 200,
"content": RailFence.encrypt(text, rail_height)
})
return jsonify({"status": 200, "content": RailFence.encrypt(text, rail_height)})

@app.route("/api/railfence/decrypt/<text>")
def railfence_decrypt(text):
rail_height = request.args.get("rail_height", RailFence.DEFAULT_RAILS)

return jsonify({
"status": 200,
"content": RailFence.decrypt(text, rail_height)
})
return jsonify({"status": 200, "content": RailFence.decrypt(text, rail_height)})

@app.route("/api/blowfish/encrypt/<text>")
def blowfish_encrypt(text):
mode = request.args.get("mode", Blowfish.DEFAULT_MODE)
return jsonify({
"status": 200,
"content": Blowfish.encrypt(text, mode)
})
return jsonify({"status": 200, "content": Blowfish.encrypt(text, mode)})

@app.route("/api/blowfish/decrypt/<text>")
def blowfish_decrypt(text):
mode = request.args.get("mode", Blowfish.DEFAULT_MODE)

return jsonify({
"status": 200,
"content": Blowfish.decrypt(text, mode)
})
return jsonify({"status": 200, "content": Blowfish.decrypt(text, mode)})


@app.route("/api/rsa/encrypt/<text>")
def rsa_encrypt(text):
n = request.args.get("n", Rsa.DEFAULT_N)
e = request.args.get("e", Rsa.DEFAULT_E)
input_n = request.args.get("n", Rsa.DEFAULT_N)
input_e = request.args.get("e", Rsa.DEFAULT_E)
chtnnh marked this conversation as resolved.
Show resolved Hide resolved

return jsonify({
"status": 200,
"content": Rsa.encrypt(text, n, e)
})
return jsonify({"status": 200, "content": Rsa.encrypt(text, input_n, input_e)})

@app.route("/api/rsa/decrypt/<text>")
def rsa_decrypt(text):
p = request.args.get("p", Rsa.DEFAULT_P)
q = request.args.get("q", Rsa.DEFAULT_Q)
e = request.args.get("e", Rsa.DEFAULT_E)
input_p = request.args.get("p", Rsa.DEFAULT_P)
input_q = request.args.get("q", Rsa.DEFAULT_Q)
input_e = request.args.get("e", Rsa.DEFAULT_E)

return jsonify({
"status": 200,
"content": Rsa.decrypt(text, p, q, e)
})
return jsonify(
{"status": 200, "content": Rsa.decrypt(text, input_p, input_q, input_e)}
)

@app.route("/api/error")
def trigger_error():
return jsonify({"status": 200, "content": "1 / 0 = {}".format(1 / 0)})

# ERROR HANDLERS
def handle_errors(e):
return jsonify({
"status": e.code,
"error": e.name,
"content": e.description
})
def handle_errors(err):
return jsonify(
{"status": err.code, "error": err.name, "content": err.description}
)

app.register_error_handler(400, handle_errors)
app.register_error_handler(500, handle_errors)
Expand Down
6 changes: 6 additions & 0 deletions encryptor/encryptors/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
"""
Encryptor - encryptors

Import and return all encryptor classes
"""

from .ceasar import *
from .railfence import *
from .blowfish import *
Expand Down
89 changes: 60 additions & 29 deletions encryptor/encryptors/blowfish.py
Original file line number Diff line number Diff line change
@@ -1,65 +1,96 @@
import json
from os import urandom
import werkzeug
"""
Encryptor - Blowfish

https://en.wikipedia.org/wiki/Blowfish_(cipher)
"""

from werkzeug.exceptions import BadRequest

import blowfish

config = {
'CIPHER_key' : b'\xf4\'\xc3(L\xd0\xcfD"B/g',
'initialization_vector' : b'7Cp\x95\x85\x029#',
"CIPHER_key": b"\xf4'\xc3(L\xd0\xcfD\"B/g",
"initialization_vector": b"7Cp\x95\x85\x029#",
}


class BlowfishException(werkzeug.exceptions.BadRequest):
class BlowfishException(BadRequest):

"""
Class defining custom Blowfish Exception
"""

def __init__(self, message):
self.message = message
BadRequest.message = message
Comment on lines -15 to +24
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need this change? We could do it differently, though, calling super.__init__(message)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Linter threw an error I didn't fully understand. But this made it go away 😆

LMK if this is unacceptable


def __str__(self):
return str(self.message)


class Blowfish:
AVAILABLE_MODES = ['cbc_cts', 'cfb', 'ofb', 'ecb_cts']
DEFAULT_MODE = 'cbc_cts'
CIPHER = blowfish.Cipher(config['CIPHER_key'])
IV = config['initialization_vector']

#This shouldn't really be called directly - it's just a way to shorten code.
#Rather just use encrypt_data() and decrypt_data()
"""
Class implementing Blowfish cipher
"""

AVAILABLE_MODES = ["cbc_cts", "cfb", "ofb", "ecb_cts"]
DEFAULT_MODE = "cbc_cts"
CIPHER = blowfish.Cipher(config["CIPHER_key"])
IV = config["initialization_vector"]

# This shouldn't really be called directly - it's just a way to shorten code.
# Rather just use encrypt_data() and decrypt_data()
@staticmethod
def _handle_data(action, data, mode = None):
if not mode: mode = Blowfish.DEFAULT_MODE
def _handle_data(action, data, mode=None):
if not mode:
mode = Blowfish.DEFAULT_MODE

elif mode not in Blowfish.AVAILABLE_MODES:
raise BlowfishException('Mode not supported: ' + str(mode))
elif mode not in Blowfish.AVAILABLE_MODES:
raise BlowfishException("Mode not supported: " + str(mode))

if action not in ['encrypt', 'decrypt']:
raise BlowfishException("Called _handle_data() with action: ' + str(action) + '. Must be `encrypt` or `decrypt`. Protip: You probably shouldn't directly call _handle_data. ")
if action not in ["encrypt", "decrypt"]:
raise BlowfishException(
"Called _handle_data() with action:" + action + ". Must be `encrypt` or `decrypt`"
)

action = '%s_%s' % (action, mode)
action = "%s_%s" % (action, mode)

#There might be a better way to implement this, which will also allow us to support multiple modes.
# There might be a better way to implement this, while still allowing multiple modes
args = [data, Blowfish.IV]
if mode == 'ecb_cts' :
if mode == "ecb_cts":
args = [data]

handled_data = b"".join(getattr(Blowfish.CIPHER, action)(*args))
return handled_data

@staticmethod
def encrypt(data, mode = None):
data = data.encode('utf-8')
encrypted_data = Blowfish._handle_data('encrypt', data, mode)
def encrypt(data, mode=None):

"""
Blowfish - Encrypt

Call helper function to encrypt input string
"""

data = data.encode("utf-8")
encrypted_data = Blowfish._handle_data("encrypt", data, mode)
encrypted_data = encrypted_data.hex()
return encrypted_data

@staticmethod
def decrypt(data, mode = None):
def decrypt(data, mode=None):

"""
Blowfish - Decrypt

Call helper functions to decrypt input string
"""

data = bytes.fromhex(data)
decrypted_data = Blowfish._handle_data('decrypt', data, mode)
print ('Data : ', decrypted_data)
decrypted_data = Blowfish._handle_data("decrypt", data, mode)
print("Data : ", decrypted_data)
try:
decrypted_data = decrypted_data.decode('utf-8')
decrypted_data = decrypted_data.decode("utf-8")
except UnicodeDecodeError:
return str(decrypted_data)
return decrypted_data
24 changes: 16 additions & 8 deletions encryptor/encryptors/ceasar.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,32 @@ def decrypt(text: str, offset: int = DEFAULT_OFFSET):
def _encrypt_letter(char: str, offset: int = DEFAULT_OFFSET):
# Encrypt uppercase characters in plain text
if char.isupper():
return chr((ord(char) + offset - Ceasar.UPPERCASE_OFFSET) %
Ceasar.ALPHABET_LENGTH + Ceasar.UPPERCASE_OFFSET)
return chr(
(ord(char) + offset - Ceasar.UPPERCASE_OFFSET) % Ceasar.ALPHABET_LENGTH
+ Ceasar.UPPERCASE_OFFSET
)
# Encrypt lowercase characters in plain text
elif char.islower():
return chr((ord(char) + offset - Ceasar.LOWERCASE_OFFSET) %
Ceasar.ALPHABET_LENGTH + Ceasar.LOWERCASE_OFFSET)
return chr(
(ord(char) + offset - Ceasar.LOWERCASE_OFFSET) % Ceasar.ALPHABET_LENGTH
+ Ceasar.LOWERCASE_OFFSET
)
else:
raise NotAllowedValue

@staticmethod
def _decrypt_letter(char: str, offset: int = DEFAULT_OFFSET):
# Decrypt uppercase characters in plain text
if char.isupper():
return chr((ord(char) - offset - Ceasar.UPPERCASE_OFFSET) %
Ceasar.ALPHABET_LENGTH + Ceasar.UPPERCASE_OFFSET)
return chr(
(ord(char) - offset - Ceasar.UPPERCASE_OFFSET) % Ceasar.ALPHABET_LENGTH
+ Ceasar.UPPERCASE_OFFSET
)
# Decrypt lowercase characters in plain text
elif char.islower():
return chr((ord(char) - offset - Ceasar.LOWERCASE_OFFSET) %
Ceasar.ALPHABET_LENGTH + Ceasar.LOWERCASE_OFFSET)
return chr(
(ord(char) - offset - Ceasar.LOWERCASE_OFFSET) % Ceasar.ALPHABET_LENGTH
+ Ceasar.LOWERCASE_OFFSET
)
else:
raise NotAllowedValue
Loading