def encrypt(key, msg, iv=None, alg="aes_128_cbc", padding="PKCS#7", b64enc=True, block_size=BLOCK_SIZE): """ :param key: The encryption key :param iv: init vector :param msg: Message to be encrypted :param padding: Which padding that should be used :param b64enc: Whether the result should be base64encoded :param block_size: If PKCS#7 padding which block size to use :return: The encrypted message """ if padding == "PKCS#7": _block_size = block_size elif padding == "PKCS#5": _block_size = 8 else: _block_size = 0 if _block_size: plen = _block_size - (len(msg) % _block_size) c = chr(plen) msg += (c * plen) cipher, iv = build_cipher(tobytes(key), iv, alg) cmsg = iv + cipher.encrypt(tobytes(msg)) if b64enc: return b64encode(cmsg) else: return cmsg
def build_cipher(key, iv, alg="aes_128_cbc"): """ Create cipher. :param key: encryption key :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ _, bits, cmode = alg.split("_") if not iv: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise AESError("Unsupported key length") if len(key) != int(bits) >> 3: raise AESError("Wrong Key length") try: return AES.new(tobytes(key), POSTFIX_MODE[cmode], tobytes(iv)), iv except KeyError: raise AESError("Unsupported chaining mode")
def build_cipher(key, iv, alg="aes_128_cbc"): """ :param key: encryption key :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ _, bits, cmode = alg.split("_") if not iv: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise AESError("Unsupported key length") if len(key) != int(bits) >> 3: raise AESError("Wrong Key length") try: return AES.new(tobytes(key), POSTFIX_MODE[cmode], tobytes(iv)), iv except KeyError: raise AESError("Unsupported chaining mode")
def encrypt(self, text): # Padding to blocksize of AES text = tobytes(text) if len(text) % 16: text += b' ' * (16 - len(text) % 16) return self.core.encrypt(tobytes(text))