Beispiel #1
0
def getmpass(txt=" to confirm this"):
    pdb = open(f'{homef}/passman.pdb', 'rb')
    iv = base64.b64decode(pdb.readline().strip(b'\n'))
    hash = pdb.readline().strip(b'\n')
    r = pdb.read()
    while True:
        pw = getpass.getpass(f'Please enter your master password{txt}: ')

        padder = PKCS7(256).padder()
        ppw = padder.update(pw.encode()) + padder.finalize()

        cipher = Cipher(algorithms.AES(ppw),
                        modes.CBC(iv),
                        backend=default_backend())
        dec = cipher.decryptor()
        rd = dec.update(r) + dec.finalize()
        padder = PKCS7(1024).unpadder()
        try:
            prd = padder.update(rd) + padder.finalize()
        except:
            print('Wrong password, try again.')
            continue

        if hash == hashlib.sha256(r).hexdigest().encode():
            break
        print('Wrong password, try again.')
    return prd, pw, iv
Beispiel #2
0
    def _encrypt_data(
            self, data: bytes) -> Tuple[Union[TripleDES, AES], bytes, bytes]:
        """Build the ciphertext of the ``messageData``.

        Args:
              data (bytes): Data to encrypt as the ``messageData`` of the SCEP Request

        Returns:
              Tuple of 3DES key, IV, and cipher text encrypted with 3DES
        """
        symkey, iv = None, None

        # TODO: this is horribad and needs abstraction
        if self._encryption_algorithm_id.native == 'tripledes_3key':
            symkey = TripleDES(os.urandom(8))
            iv = os.urandom(8)
        elif self._encryption_algorithm_id.native == 'aes128_cbc':
            symkey = AES(os.urandom(16))
            iv = os.urandom(16)

        cipher = Cipher(symkey, modes.CBC(iv), backend=default_backend())
        encryptor = cipher.encryptor()

        if self._encryption_algorithm_id.native == 'tripledes_3key':
            padder = PKCS7(TripleDES.block_size).padder()
        elif self._encryption_algorithm_id.native == 'aes128_cbc':
            padder = PKCS7(AES.block_size).padder()

        padded = padder.update(data)
        padded += padder.finalize()

        ciphertext = encryptor.update(padded) + encryptor.finalize()

        return symkey, iv, ciphertext
class EncryptionManager(object):
    key: bytes = token_bytes(32)
    iv: bytes = token_bytes(16)
    c: Cipher = Cipher(
                    algorithms.AES(key),
                    modes.CBC(iv),
                    backend=default_backend()
            )
    encryptor: Callable = c.encryptor()
    decryptor: Callable = c.decryptor()
    padder: Callable = PKCS7(128).padder()
    unpadder: Callable = PKCS7(128).unpadder()
    
    def update_encryptor(self, plaintext: bytes) -> bytes:
        return self.encryptor.update(self.padder.update(plaintext))
    
    def finalize_encryptor(self):
        return self.encryptor.update(self.padder.finalize()) \
        + self.encryptor.finalize()
    
    def update_decryptor(self, ciphertext: bytes) -> bytes:
        return self.unpadder.update(self.decryptor.update(ciphertext))
                    
    def finalize_decryptor(self) -> bytes:
        return self.unpadder.update(self.decryptor.finalize()) \
        + self.unpadder.finalize()
Beispiel #4
0
    def __init__(self, key_len=32, key=None, msg_padding='PKCS7'):
        Encrypter.__init__(self)
        if key:
            self.key = key
        else:
            self.key = os.urandom(key_len)

        if msg_padding == 'PKCS7':
            self.padder = PKCS7(128).padder()
            self.unpadder = PKCS7(128).unpadder()
Beispiel #5
0
    def __init__(self, key_len=32, key=None, msg_padding="PKCS7"):
        Encrypter.__init__(self)
        if key:
            self.key = key
        else:
            self.key = os.urandom(key_len)

        if msg_padding == "PKCS7":
            self.padder = PKCS7(128).padder()
            self.unpadder = PKCS7(128).unpadder()
        else:
            raise Unsupported("Message padding: {}".format(msg_padding))

        self.iv = None
Beispiel #6
0
def aes_cbc_dec(aesKey, bsEncMsg, bsMacMsg):
    '''
    AuthenticatedEncryption - Check mac then decrypt given encrypted message.
    '''
    ### Prepare for mac
    sha256 = SHA256()
    hmac = HMAC(aesKey, sha256, default_backend())
    ### do mac
    hmac.update(bsEncMsg)
    macMsg = hmac.finalize()
    if (macMsg != bsMacMsg):
        raise Exception("ERRR:AEDecrypt:Mismatch, skipping")
        return None
    ### Prepare for decryption
    blockLen = 16
    iv = os.urandom(blockLen)
    aes = AES(aesKey)
    cbc = CBC(iv)
    aesCbc = Cipher(aes, cbc, default_backend())
    aesCbcDec = aesCbc.decryptor()
    ### do decrypt
    decMsg = aesCbcDec.update(bsEncMsg)
    decFina = aesCbcDec.finalize()
    decMsg = decMsg + decFina
    # do pkcs7 depadding
    unpad = PKCS7(blockLen * 8).unpadder()
    decMsg = unpad.update(decMsg)
    decMsg += unpad.finalize()
    # Discard the initial random block, as corresponding enc and this dec uses
    # non communicated random iv and inturn discardable random 0th block
    decMsg = decMsg[blockLen:]
    return decMsg
Beispiel #7
0
def verifyToken(token, mustBeAdmin):
    if token is None:
        return None, None
    tokenB = base64.b64decode(token)
    tokenS = tokenB.decode("utf-8")
    tokenJS = json.JSONDecoder().decode(tokenS)
    id2 = tokenJS["id"]
    nowS = tokenJS["now"]
    sharedkey = id2sharedKey.get(id2)
    if sharedkey is None:
        return None, None
    username = id2username.get(id2)
    if username is None:
        return None, None
    if mustBeAdmin and username != "admin":
        return None, None
    nowEnc = base64.b64decode(tokenJS["nowEnc"])
    ivS = tokenJS["iv"]
    ivB = base64.b64decode(ivS)
    aesAlg = algorithms.AES(sharedkey)
    cipher = Cipher(aesAlg, modes.CBC(ivB))
    decryptor = cipher.decryptor()
    nowDecB = decryptor.update(nowEnc) + decryptor.finalize()
    unpadder = PKCS7(128).unpadder()
    nowDecB = unpadder.update(nowDecB) + unpadder.finalize()
    nowDecS = nowDecB.decode("utf-8")
    if nowS != nowDecS:  # so sharedKey was not working
        return None, None
    now = datetime.utcnow()
    clntNow = datetime.utcfromtimestamp(int(nowS) / 1000)
    diff = int((now - clntNow).total_seconds())
    if -600 < diff < 600: # clntNow within 10 minutes before or after now
        return expiration(id2), username
    return None, None
Beispiel #8
0
    def test_validate_encryption(self):
        # Arrange
        self.bbs.require_encryption = True
        kek = KeyWrapper('key1')
        self.bbs.key_encryption_key = kek
        blob_name = self._create_small_blob('block_blob')

        # Act
        self.bbs.require_encryption = False
        self.bbs.key_encryption_key = None
        blob = self.bbs.get_blob_to_bytes(self.container_name, blob_name)

        encryption_data = _dict_to_encryption_data(
            loads(blob.metadata['encryptiondata']))
        iv = encryption_data.content_encryption_IV
        content_encryption_key = _validate_and_unwrap_cek(
            encryption_data, kek, None)
        cipher = _generate_AES_CBC_cipher(content_encryption_key, iv)
        decryptor = cipher.decryptor()
        unpadder = PKCS7(128).unpadder()

        content = decryptor.update(blob.content) + decryptor.finalize()
        content = unpadder.update(content) + unpadder.finalize()

        self.assertEqual(self.bytes, content)
Beispiel #9
0
    async def _test_validate_encryption_async(self):
        # Arrange
        await self._setup()
        self.bsc.require_encryption = True
        kek = KeyWrapper('key1')
        self.bsc.key_encryption_key = kek
        blob = await self._create_small_blob(BlobType.BlockBlob)

        # Act
        blob.require_encryption = False
        blob.key_encryption_key = None
        content = await blob.download_blob()
        data = await content.content_as_bytes()

        encryption_data = _dict_to_encryption_data(
            loads(content.properties.metadata['encryptiondata']))
        iv = encryption_data.content_encryption_IV
        content_encryption_key = _validate_and_unwrap_cek(
            encryption_data, kek, None)
        cipher = _generate_AES_CBC_cipher(content_encryption_key, iv)
        decryptor = cipher.decryptor()
        unpadder = PKCS7(128).unpadder()

        content = decryptor.update(data) + decryptor.finalize()
        content = unpadder.update(content) + unpadder.finalize()

        self.assertEqual(self.bytes, content)
Beispiel #10
0
    def decrypt(self, k, a, iv, e, t):
        """ Decrypt according to the selected encryption and hashing
        functions.
        :param k: Encryption key (optional)
        :param a: Additional Authenticated Data
        :param iv: Initialization Vector
        :param e: Ciphertext
        :param t: Authentication Tag

        Returns plaintext or raises an error
        """
        hkey = k[:self.keysize]
        dkey = k[self.keysize:]

        # verify mac
        if not constant_time.bytes_eq(t, self._mac(hkey, a, iv, e)):
            raise InvalidJWEData('Failed to verify MAC')

        # decrypt
        cipher = Cipher(algorithms.AES(dkey), modes.CBC(iv),
                        backend=self.backend)
        decryptor = cipher.decryptor()
        d = decryptor.update(e) + decryptor.finalize()
        unpadder = PKCS7(self.blocksize).unpadder()
        return unpadder.update(d) + unpadder.finalize()
Beispiel #11
0
    def decrypter_fichier(self, nom_fichier, secret, iv):
        """
        Utilise la cle privee en memoire pour decrypter le contenu.
        :param contenu:
        :return:
        """
        self._logger.info(
            '------- JavascriptPythonSymetric.decrypter_fichier() ----------')
        keyb = b64decode(secret)
        ivb = b64decode(iv)

        with open('/tmp/dict_encrypt/%s' % nom_fichier, 'rb') as fichier:
            contenub = fichier.read()

        cipher = Cipher(algorithms.AES(keyb),
                        modes.CBC(ivb),
                        backend=default_backend())
        decryptor = cipher.decryptor()

        resultat = decryptor.update(contenub) + decryptor.finalize()
        # self._logger.info("Message decrypte (%d)" % len(resultat))

        # On utilise AES 256, blocks de taille 256 bits.
        unpadder = PKCS7(128).unpadder()
        resultat_unpadded = unpadder.update(resultat) + unpadder.finalize()
        # self._logger.info("Message unpadded (%d):\n%s" % (len(resultat_unpadded), binascii.hexlify(resultat_unpadded)))

        # resultat_string = resultat_unpadded.decode('utf-8')
        # self._logger.info("Message string: %s" % resultat_string)

        with open('/tmp/dict_encrypt/decrypt/%s' % nom_fichier,
                  'wb') as output:
            output.write(resultat_unpadded)
Beispiel #12
0
def decrypt_blob_bytes(data: bytes, length: int, key: bytes, iv: bytes) -> bytes:
    if len(data) != length:
        raise ValueError("unexpected length")
    cipher = Cipher(AES(key), modes.CBC(iv), backend=BACKEND)
    unpadder = PKCS7(AES.block_size).unpadder()
    decryptor = cipher.decryptor()
    return unpadder.update(decryptor.update(data) + decryptor.finalize()) + unpadder.finalize()
    def test_validate_encryption(self, resource_group, location,
                                 storage_account, storage_account_key):
        self._setup(storage_account.name, storage_account_key)
        self.bsc.require_encryption = True
        kek = KeyWrapper('key1')
        self.bsc.key_encryption_key = kek
        blob = self._create_small_blob(BlobType.BlockBlob)

        # Act
        blob.require_encryption = False
        blob.key_encryption_key = None
        content = blob.download_blob()
        data = content.content_as_bytes()

        encryption_data = _dict_to_encryption_data(
            loads(content.properties.metadata['encryptiondata']))
        iv = encryption_data.content_encryption_IV
        content_encryption_key = _validate_and_unwrap_cek(
            encryption_data, kek, None)
        cipher = _generate_AES_CBC_cipher(content_encryption_key, iv)
        decryptor = cipher.decryptor()
        unpadder = PKCS7(128).unpadder()

        content = decryptor.update(data) + decryptor.finalize()
        content = unpadder.update(content) + unpadder.finalize()

        self.assertEqual(self.bytes, content)
Beispiel #14
0
    def __call__(self, element, mac=None):
        algo, mode, klen = fetch(element, "./xenc:EncryptionMethod/@Algorithm",
                                 convertAlgorithm)
        data = fetch(element, "./xenc:CipherData/xenc:CipherValue/text()",
                     base64.b64decode)

        # Make sure the key is the right length.
        if len(self.__key) * 8 != klen:
            raise ValidationError("Invalid key length!")

        # If a MAC is present, perform validation.
        if mac:
            tmp = self.__hmac.copy()
            tmp.update(data)
            try:
                tmp.verify(mac)
            except InvalidSignature as e:
                raise ValidationError("MAC validation failed!", e)

        iv = data[:algo.block_size // 8]
        data = data[len(iv):]

        algorithm = algo(self.__key)
        cipher = Cipher(algorithm, mode(iv), default_backend())
        decryptor = cipher.decryptor()
        padded = decryptor.update(data)
        padded += decryptor.finalize()

        unpadder = PKCS7(algorithm.block_size).unpadder()
        out = unpadder.update(padded)
        out += unpadder.finalize()

        return out
Beispiel #15
0
 def __init__(self, key: bytes):
     self.buf = deque()
     self.key = key
     self.algorithm = algorithms.AES
     self.block_size = int(self.algorithm.block_size / 8)
     self.unpadder = PKCS7(self.block_size * 8).unpadder()
     self.cipher = None
    def decrypt(self, cipher_text, iv=None, aad=None, tag=None):
        cipher_text = six.ensure_binary(cipher_text)
        try:
            iv = six.ensure_binary(iv)
            mode = self._mode(iv)
            if mode.name == "GCM":
                if tag is None:
                    raise ValueError("tag cannot be None")
                cipher = aead.AESGCM(self._key)
                cipher_text_and_tag = cipher_text + tag
                try:
                    plain_text = cipher.decrypt(iv, cipher_text_and_tag, aad)
                except InvalidTag:
                    raise JWEError("Invalid JWE Auth Tag")
            else:
                cipher = Cipher(algorithms.AES(self._key), mode,
                                backend=default_backend())
                decryptor = cipher.decryptor()
                padded_plain_text = decryptor.update(cipher_text)
                padded_plain_text += decryptor.finalize()
                unpadder = PKCS7(algorithms.AES.block_size).unpadder()
                plain_text = unpadder.update(padded_plain_text)
                plain_text += unpadder.finalize()

            return plain_text
        except Exception as e:
            raise JWEError(e)
Beispiel #17
0
    def decrypt(token):  # lint-amnesty, pylint: disable=missing-function-docstring
        try:
            base64_decoded = urlsafe_b64decode(token)
        except (TypeError, Error):
            raise UsernameDecryptionException("base64url")  # lint-amnesty, pylint: disable=raise-missing-from

        if len(base64_decoded) < AES_BLOCK_SIZE_BYTES:
            raise UsernameDecryptionException("initialization_vector")

        initialization_vector = base64_decoded[:AES_BLOCK_SIZE_BYTES]
        aes_encrypted = base64_decoded[AES_BLOCK_SIZE_BYTES:]
        aes_cipher = UsernameCipher._get_aes_cipher(initialization_vector)
        decryptor = aes_cipher.decryptor()
        unpadder = PKCS7(AES.block_size).unpadder()

        try:
            decrypted = decryptor.update(aes_encrypted) + decryptor.finalize()
        except ValueError:
            raise UsernameDecryptionException("aes")  # lint-amnesty, pylint: disable=raise-missing-from

        try:
            unpadded = unpadder.update(decrypted) + unpadder.finalize()
            if len(unpadded) == 0:
                raise UsernameDecryptionException("padding")
            return unpadded
        except ValueError:
            raise UsernameDecryptionException("padding")  # lint-amnesty, pylint: disable=raise-missing-from
Beispiel #18
0
    def decrypt(token):
        try:
            base64_decoded = urlsafe_b64decode(token)
        except TypeError:
            raise UsernameDecryptionException("base64url")

        if len(base64_decoded) < AES_BLOCK_SIZE_BYTES:
            raise UsernameDecryptionException("initialization_vector")

        initialization_vector = base64_decoded[:AES_BLOCK_SIZE_BYTES]
        aes_encrypted = base64_decoded[AES_BLOCK_SIZE_BYTES:]
        aes_cipher = UsernameCipher._get_aes_cipher(initialization_vector)
        decryptor = aes_cipher.decryptor()
        unpadder = PKCS7(AES.block_size).unpadder()

        try:
            decrypted = decryptor.update(aes_encrypted) + decryptor.finalize()
        except ValueError:
            raise UsernameDecryptionException("aes")

        try:
            unpadded = unpadder.update(decrypted) + unpadder.finalize()
            if len(unpadded) == 0:
                raise UsernameDecryptionException("padding")
            return unpadded
        except ValueError:
            raise UsernameDecryptionException("padding")
Beispiel #19
0
 def encrypt(self, plain_text, aad=None):
     plain_text = ensure_binary(plain_text)
     try:
         iv = get_random_bytes(algorithms.AES.block_size // 8)
         mode = self._mode(iv)
         if mode.name == "GCM":
             cipher = aead.AESGCM(self._key)
             cipher_text_and_tag = cipher.encrypt(iv, plain_text, aad)
             cipher_text = cipher_text_and_tag[:len(cipher_text_and_tag) -
                                               16]
             auth_tag = cipher_text_and_tag[-16:]
         else:
             cipher = Cipher(algorithms.AES(self._key),
                             mode,
                             backend=default_backend())
             encryptor = cipher.encryptor()
             padder = PKCS7(algorithms.AES.block_size).padder()
             padded_data = padder.update(plain_text)
             padded_data += padder.finalize()
             cipher_text = encryptor.update(
                 padded_data) + encryptor.finalize()
             auth_tag = None
         return iv, cipher_text, auth_tag
     except Exception as e:
         raise JWEError(e)
Beispiel #20
0
    def encrypt(self, k, a, m):
        """ Encrypt according to the selected encryption and hashing
        functions.

        :param k: Encryption key (optional)
        :param a: Additional Authentication Data
        :param m: Plaintext

        Returns a dictionary with the computed data.
        """
        hkey = k[:self.keysize]
        ekey = k[self.keysize:]

        # encrypt
        iv = os.urandom(self.blocksize // 8)
        cipher = Cipher(algorithms.AES(ekey), modes.CBC(iv),
                        backend=self.backend)
        encryptor = cipher.encryptor()
        padder = PKCS7(self.blocksize).padder()
        padded_data = padder.update(m) + padder.finalize()
        e = encryptor.update(padded_data) + encryptor.finalize()

        # mac
        t = self._mac(hkey, a, iv, e)

        return (iv, e, t)
Beispiel #21
0
def build(payload, signing_key, key, iv, backend):
    backend = signing_key._backend

    signature = signing_key.sign(
        payload.decode('utf-8').encode('utf-16-le'), PKCS1v15(), SHA1())

    sign_doc = etree.Element('SIGNATURE')
    etree.SubElement(sign_doc, 'VERSION').text = '1.0'
    etree.SubElement(
        sign_doc,
        'DIGEST').text = binascii.hexlify(signature).decode().upper()
    _key_to_xml(signing_key.public_key(), sign_doc)

    signed = b'\xef\xbb\xbf' + payload + etree.tostring(sign_doc)

    compressor = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
    compressed = compressor.compress(signed) + compressor.flush()

    padder = PKCS7(len(iv) * 8).padder()
    padded = padder.update(compressed) + padder.finalize()

    encryptor = Cipher(AES(key), CBC(iv), backend=backend).encryptor()
    encrypted = encryptor.update(padded) + encryptor.finalize()

    doc = etree.Element('ARCHIVE')
    doc.set('TYPE', 'GEMSTONE')
    node = etree.SubElement(doc, 'RADIO')
    node.set('VERSION', '1')
    node.set('ENCODING', 'Base64')
    node.text = base64.b64encode(encrypted)

    return etree.tostring(doc)
Beispiel #22
0
    async def _decrypt_v1(self,
                          file_data: bytes,
                          metadata: Dict[str, str],
                          range_start: Optional[int] = None) -> bytes:
        if range_start:
            raise DecryptError(
                'Cant do range get when not using KMS encryption')

        decryption_key = base64.b64decode(metadata['x-amz-key'])
        material_description = json.loads(metadata['x-amz-matdesc'])

        aes_key = await self._crypto_context.get_decryption_aes_key(
            decryption_key, material_description)

        # x-amz-key - Contains base64 encrypted key
        # x-amz-iv - AES IVs
        # x-amz-matdesc - JSON Description of client-side master key (used as encryption context as is)
        # x-amz-unencrypted-content-length - Unencrypted content length

        iv = base64.b64decode(metadata['x-amz-iv'])

        # TODO look at doing AES as stream

        # AES/CBC/PKCS5Padding
        aescbc = Cipher(AES(aes_key), CBC(iv),
                        backend=self._backend).decryptor()
        padded_result = await self._loop.run_in_executor(
            None, lambda: (aescbc.update(file_data) + aescbc.finalize()))

        unpadder = PKCS7(AES.block_size).unpadder()
        result = await self._loop.run_in_executor(
            None, lambda:
            (unpadder.update(padded_result) + unpadder.finalize()))

        return result
Beispiel #23
0
 def encrypt(username):
     initialization_vector = os.urandom(AES_BLOCK_SIZE_BYTES)
     aes_cipher = UsernameCipher._get_aes_cipher(initialization_vector)
     encryptor = aes_cipher.encryptor()
     padder = PKCS7(AES.block_size).padder()
     padded = padder.update(username.encode("utf-8")) + padder.finalize()
     return urlsafe_b64encode(initialization_vector + encryptor.update(padded) + encryptor.finalize())
Beispiel #24
0
    def encrypt(self, pt, is_filename=False):
        """
        Encrypt and authenticate the given plaintext using AES and HMAC.
        if is_filename is True, the IV will be deterministically generated (derived from secret||pt),
        and the returned data will all be concatenated (not a tuple)
        :param pt: (bytes) plaintext
        :param is_filename: (bool) encrypting for filename
        :return: encrypted data: Union(Tuple, bytes) (iv||ct, tag) or iv||ct||tag in case of filename
                    iv = initialization vector (128 bits)
                    ct = ciphertext (encrypted message)
                    tag = MAC tag (256 bits)
        """
        # pad the plaintext to make its size a multiple of 256 bits (for CBC)
        padder = PKCS7(256).padder()
        padded_pt = padder.update(pt) + padder.finalize()

        iv = self.derive_key(self._secret +
                             pt)[:16] if is_filename else os.urandom(16)
        cipher = Cipher(algorithms.AES(self._cipher_key), modes.CBC(iv),
                        default_backend())
        encryptor = cipher.encryptor()
        ct = encryptor.update(padded_pt) + encryptor.finalize()

        tag = self.get_hmac_tag(iv + ct)
        return iv + ct + tag if is_filename else (iv + ct, tag)
Beispiel #25
0
def pad(data):
    """ Pad the given `data` such that it fits into the proper AES block size """

    if six.PY3 and not isinstance(data, (bytes, bytearray)):
        data = six.b(data)

    padder = PKCS7(AES.block_size).padder()
    return padder.update(data) + padder.finalize()
Beispiel #26
0
def encrypt_blob_bytes(key: bytes, iv: bytes, unencrypted: bytes) -> typing.Tuple[bytes, str]:
    cipher = Cipher(AES(key), modes.CBC(iv), backend=BACKEND)
    padder = PKCS7(AES.block_size).padder()
    encryptor = cipher.encryptor()
    encrypted = encryptor.update(padder.update(unencrypted) + padder.finalize()) + encryptor.finalize()
    digest = get_lbry_hash_obj()
    digest.update(encrypted)
    return encrypted, digest.hexdigest()
Beispiel #27
0
def aes_encrypt(secret, value):
    key = double_sha256(secret)
    init_vector = os.urandom(16)
    encryptor = Cipher(AES(key), modes.CBC(init_vector), default_backend()).encryptor()
    padder = PKCS7(AES.block_size).padder()
    padded_data = padder.update(value) + padder.finalize()
    encrypted_data2 = encryptor.update(padded_data) + encryptor.finalize()
    return base64.b64encode(encrypted_data2)
Beispiel #28
0
def aes_decrypt(secret, value):
    data = base64.b64decode(value)
    key = double_sha256(secret)
    init_vector, data = data[:16], data[16:]
    decryptor = Cipher(AES(key), modes.CBC(init_vector), default_backend()).decryptor()
    unpadder = PKCS7(AES.block_size).unpadder()
    result = unpadder.update(decryptor.update(data)) + unpadder.finalize()
    return result
Beispiel #29
0
def better_aes_encrypt(secret: str, value: bytes) -> bytes:
    init_vector = os.urandom(16)
    key = scrypt(secret.encode(), salt=init_vector)
    encryptor = Cipher(AES(key), modes.CBC(init_vector), default_backend()).encryptor()
    padder = PKCS7(AES.block_size).padder()
    padded_data = padder.update(value) + padder.finalize()
    encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
    return base64.b64encode(b's:8192:16:1:' + init_vector + encrypted_data)
Beispiel #30
0
def pkcs7_unpadding(data: bytes, block_size):
    """
    Args:
        block_size (int): the length of bytes, no the length of bit
    """

    unpadder = PKCS7(block_size * 8).unpadder()
    return unpadder.update(data) + unpadder.finalize()