def verify(self, rawdata, signature): try: binary_sign = base64.b64decode(signature) except binasciiError: return False blocks = split(rawdata.encode(), BLOCK_SIZE) signature_blocks = split(binary_sign, 256) verified_block = [] for raw_block, sign_block in zip(blocks, signature_blocks): c = int.from_bytes(sign_block, 'big') original = pow(c, self.e, self.n) signed = _int2Bytes(original) verified_block.append(signed) assembled = assemble(verified_block) return assembled == bytes(rawdata.encode())
def sign(self, rawdata): # Compute a fixed-length hash, so we don't have to deal with padding blocks = split(rawdata.encode(), BLOCK_SIZE) result = [] for b in blocks: raw = int.from_bytes(b, 'big') sign = pow(raw, self.d, self.n) signature_chunk = _int2Bytes(sign) result.append(signature_chunk) representable = base64.b64encode(b"".join(result)) return representable
def test_long_word(self): rawdata = bytes(randomword(30).encode()) blocks = split(rawdata, 15) self.assertEqual(assemble(blocks), rawdata) self.assertNotEqual(assemble(blocks[:-1]), rawdata)
def test_resplit(self): rawdata = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" blocks = split(rawdata, 5) self.assertEqual([b"ABCDE", b"FGHIJ", b"KLMNO", b"PQRST", b"UVWXY", b"Z\0\4\0\0"], blocks)
def test_split(self): rawdata = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" blocks = split(rawdata, 16) self.assertEqual(b"ABCDEFGHIJKLMNOP", blocks[0]) self.assertEqual(b"QRSTUVWXYZ\0\6\0\0\0\0", blocks[1])
def test_no_padd(self): rawdata = bytes(randomword(30).encode()) blocks = split(rawdata, 10) self.assertEqual(assemble(blocks), rawdata)
def test_all_word(self): for i in range(1, 2 ** 10): rawdata = bytes(randomword(i).encode()) blocks = split(rawdata, 15) self.assertEqual(assemble(blocks), rawdata)