Skip to content

Commit 2d67278

Browse files
committed
Enhanced AES test
1 parent 1e7a54f commit 2d67278

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

Diff for: src/crypto.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def decrypt(self, data: str) -> str:
5252
class AESCipher(SymmetricAlgorithm):
5353
# Sets the key and block size
5454
def __init__(self, key):
55-
self.key = hashlib.sha256(key.encode()).digest()
55+
self._key = hashlib.sha256(key.encode()).digest() if isinstance(key, str) else None
5656
self.bs = 32
5757

5858
# Pad data up to block size
@@ -63,6 +63,9 @@ def unpad(self, s):
6363
return s[:-ord(s[len(s) - 1:])]
6464

6565
def encrypt(self, data: str):
66+
if not isinstance(self.key, str):
67+
raise ValueError('Invalid key')
68+
6669
data = self.pad(data)
6770
iv = Random.new().read(AES.block_size)
6871
aes = AES.new(self.key, AES.MODE_CBC, iv)
@@ -71,6 +74,9 @@ def encrypt(self, data: str):
7174
return base64.b64encode(C).decode('utf-8')
7275

7376
def decrypt(self, data: str) -> str:
77+
if not isinstance(self.key, str):
78+
raise ValueError('Invalid key')
79+
7480
data = base64.b64decode(data)
7581
iv = data[:AES.block_size]
7682
aes = AES.new(self.key, AES.MODE_CBC, iv)

Diff for: tests/test_aes.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ def test_cipher(self):
99

1010
message = ''.join(random.choice(string.ascii_uppercase + string.digits +
1111
string.ascii_lowercase) for _ in range(100))
12-
key = random.randint(0,32)
13-
12+
key = ''.join(random.choice(string.ascii_uppercase + string.digits +
13+
string.ascii_lowercase) for _ in range(32))
14+
1415
# check cipher without key
1516
try:
1617
C = cipher.encrypt(message)

0 commit comments

Comments
 (0)