This repository has been archived by the owner on Aug 10, 2019. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This makes SimpleAES compatible with many of the other AES implementations out there, most notably CryptoJS. It uses PKCS7-style padding for the byte stream, which is a revertible, unambiguous padding that avoids data loss while not requiring length announcements in the stream header. This is the default pad-encoding for CryptoJS and possibly many more algorithms out there.
- Loading branch information
Showing
2 changed files
with
77 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
from binascii import hexlify, unhexlify | ||
|
||
|
||
class InvalidBlockSizeError(Exception): | ||
"""Raised for invalid block sizes""" | ||
pass | ||
|
||
|
||
class PKCS7Encoder(): | ||
"""Technique for padding a string as defined in RFC 2315, section 10.3, | ||
note #2. | ||
""" | ||
def __init__(self, block_size=16): | ||
if block_size < 1 or block_size > 99: | ||
raise InvalidBlockSizeError('The block size must be between 1 ' \ | ||
'and 99') | ||
self.block_size = block_size | ||
|
||
def encode(self, text): | ||
text_length = len(text) | ||
amount_to_pad = self.block_size - (text_length % self.block_size) | ||
if amount_to_pad == 0: | ||
amount_to_pad = self.block_size | ||
pad = unhexlify('%02d' % amount_to_pad) | ||
return text + pad * amount_to_pad | ||
|
||
def decode(self, text): | ||
pad = int(hexlify(text[-1])) | ||
return text[:-pad] |