Skip to content

Commit 163c422

Browse files
author
auxten
committed
Add unpad test cases
1 parent 62d27e2 commit 163c422

File tree

2 files changed

+26
-15
lines changed

2 files changed

+26
-15
lines changed

pycovenantsql/e2ee.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,10 @@
55

66

77
BLOCK_SIZE = AES.block_size # Bytes
8-
pad = lambda s: s + ((BLOCK_SIZE - len(s) % BLOCK_SIZE) *
9-
chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)).encode('utf-8')
10-
11-
12-
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
138

149
salt = unhexlify("3fb8877d37fdc04e4a4765EFb8ab7d36")
1510

11+
1612
class PaddingError(Exception):
1713
"""Exception raised for errors in the padding.
1814
@@ -23,19 +19,21 @@ class PaddingError(Exception):
2319
def __init__(self, message):
2420
self.message = message
2521

22+
pad = lambda s: s + ((BLOCK_SIZE - len(s) % BLOCK_SIZE) *
23+
chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)).encode('utf-8')
2624

2725
def unpad(s):
28-
inLen = len(s)
29-
if inLen == 0:
26+
in_len = len(s)
27+
if in_len == 0:
3028
raise PaddingError("empty input")
31-
padChar = s[-1]
32-
padLen = ord(s[inLen-1:])
33-
if padLen > BLOCK_SIZE:
29+
pad_char = s[-1]
30+
pad_len = ord(s[in_len-1:])
31+
if pad_len > BLOCK_SIZE:
3432
raise PaddingError("padding length > 16")
35-
for i in s[inLen-padLen:]:
36-
if i != padChar:
37-
raise PaddingError("unknown padding char")
38-
return s[:-padLen]
33+
for i in s[in_len-pad_len:]:
34+
if i != pad_char:
35+
raise PaddingError("unexpected padding char")
36+
return s[:-pad_len]
3937

4038

4139
# kdf does 2 times sha256 and takes the first 16 bytes

pycovenantsql/tests/test_e2ee.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# coding: utf-8
22

33
import unittest
4-
from pycovenantsql.e2ee import encrypt, decrypt
4+
from pycovenantsql.e2ee import encrypt, decrypt, unpad, PaddingError
55
from binascii import hexlify, unhexlify
66

77
# Test cases for all implementations.
@@ -65,3 +65,16 @@ def test_enc_dec(self):
6565
self.assertEqual(unhexlify(case["raw"]), dec)
6666
dec2 = decrypt(unhexlify(case["possibleEncrypted"]), case["pass"].encode())
6767
self.assertEqual(unhexlify(case["raw"]), dec2)
68+
69+
def test_unpad_error(self):
70+
self.assertEqual(
71+
unpad(unhexlify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa01")),
72+
unhexlify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
73+
)
74+
self.assertEqual(
75+
unpad(unhexlify("aaaaaaaaaaaaaaaaaaaaaaaaaaaa0202")),
76+
unhexlify("aaaaaaaaaaaaaaaaaaaaaaaaaaaa")
77+
)
78+
self.assertRaisesRegex(PaddingError, "unexpected padding char", unpad, unhexlify("aaaaaaaaaaaaaaaaaaaaaaaaaaaa0102"))
79+
self.assertRaisesRegex(PaddingError, "padding length > 16", unpad, unhexlify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))
80+
self.assertRaisesRegex(PaddingError, "empty input", unpad, unhexlify(""))

0 commit comments

Comments
 (0)