Python cryptography.hazmat.primitives.ciphers.Cipher() Examples

The following are 30 code examples of cryptography.hazmat.primitives.ciphers.Cipher(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.hazmat.primitives.ciphers , or try the search function .
Example #1
Source File: fernet.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _encrypt_from_parts(self, data, current_time, iv):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
        )

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac) 
Example #2
Source File: jwa.py    From jwcrypto with GNU Lesser General Public License v3.0 6 votes vote down vote up
def encrypt(self, k, a, m):
        """ Encrypt accoriding 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.
        """
        iv = _randombits(96)
        cipher = Cipher(algorithms.AES(k), modes.GCM(iv),
                        backend=self.backend)
        encryptor = cipher.encryptor()
        encryptor.authenticate_additional_data(a)
        e = encryptor.update(m) + encryptor.finalize()

        return (iv, e, encryptor.tag) 
Example #3
Source File: fernet.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _encrypt_from_parts(self, data, current_time, iv):
        utils._check_bytes("data", data)

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
        )

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac) 
Example #4
Source File: jwa.py    From jwcrypto with GNU Lesser General Public License v3.0 6 votes vote down vote up
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[:_inbytes(self.keysize)]
        dkey = k[_inbytes(self.keysize):]

        # verify mac
        if not constant_time.bytes_eq(t, self._mac(hkey, a, iv, e)):
            raise InvalidSignature('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() 
Example #5
Source File: keywrap.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _unwrap_core(wrapping_key, a, r, backend):
    # Implement RFC 3394 Key Unwrap - 2.2.2 (index method)
    decryptor = Cipher(AES(wrapping_key), ECB(), backend).decryptor()
    n = len(r)
    for j in reversed(range(6)):
        for i in reversed(range(n)):
            # pack/unpack are safe as these are always 64-bit chunks
            atr = struct.pack(
                ">Q", struct.unpack(">Q", a)[0] ^ ((n * j) + i + 1)
            ) + r[i]
            # every decryption operation is a discrete 16 byte chunk so
            # it is safe to reuse the decryptor for the entire operation
            b = decryptor.update(atr)
            a = b[:8]
            r[i] = b[-8:]

    assert decryptor.finalize() == b""
    return a, r 
Example #6
Source File: jwa.py    From jwcrypto with GNU Lesser General Public License v3.0 6 votes vote down vote up
def unwrap(self, key, bitsize, ek, headers):
        rk = self._get_key(key, 'decrypt')

        if 'iv' not in headers:
            raise ValueError('Invalid Header, missing "iv" parameter')
        iv = base64url_decode(headers['iv'])
        if 'tag' not in headers:
            raise ValueError('Invalid Header, missing "tag" parameter')
        tag = base64url_decode(headers['tag'])

        cipher = Cipher(algorithms.AES(rk), modes.GCM(iv, tag),
                        backend=self.backend)
        decryptor = cipher.decryptor()
        cek = decryptor.update(ek) + decryptor.finalize()
        if _bitsize(cek) != bitsize:
            raise InvalidJWEKeyLength(bitsize, _bitsize(cek))
        return cek 
Example #7
Source File: keywrap.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _unwrap_core(wrapping_key, a, r, backend):
    # Implement RFC 3394 Key Unwrap - 2.2.2 (index method)
    decryptor = Cipher(AES(wrapping_key), ECB(), backend).decryptor()
    n = len(r)
    for j in reversed(range(6)):
        for i in reversed(range(n)):
            # pack/unpack are safe as these are always 64-bit chunks
            atr = struct.pack(
                ">Q", struct.unpack(">Q", a)[0] ^ ((n * j) + i + 1)
            ) + r[i]
            # every decryption operation is a discrete 16 byte chunk so
            # it is safe to reuse the decryptor for the entire operation
            b = decryptor.update(atr)
            a = b[:8]
            r[i] = b[-8:]

    assert decryptor.finalize() == b""
    return a, r 
Example #8
Source File: keywrap.py    From teleport with Apache License 2.0 6 votes vote down vote up
def aes_key_wrap_with_padding(wrapping_key, key_to_wrap, backend):
    if len(wrapping_key) not in [16, 24, 32]:
        raise ValueError("The wrapping key must be a valid AES key length")

    aiv = b"\xA6\x59\x59\xA6" + struct.pack(">i", len(key_to_wrap))
    # pad the key to wrap if necessary
    pad = (8 - (len(key_to_wrap) % 8)) % 8
    key_to_wrap = key_to_wrap + b"\x00" * pad
    if len(key_to_wrap) == 8:
        # RFC 5649 - 4.1 - exactly 8 octets after padding
        encryptor = Cipher(AES(wrapping_key), ECB(), backend).encryptor()
        b = encryptor.update(aiv + key_to_wrap)
        assert encryptor.finalize() == b""
        return b
    else:
        r = [key_to_wrap[i:i + 8] for i in range(0, len(key_to_wrap), 8)]
        return _wrap_core(wrapping_key, aiv, r, backend) 
Example #9
Source File: fernet.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _encrypt_from_parts(self, data, current_time, iv):
        utils._check_bytes("data", data)

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
        )

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac) 
Example #10
Source File: encrypted_queries_tools.py    From github-token with GNU General Public License v3.0 6 votes vote down vote up
def decrypt(message, receiver_private_key):
    point = message[0:65]
    tag = message[65:81]
    ciphertext = message[81:]
    sender_public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), point)
    sender_public_key = sender_public_numbers.public_key(backend)
    shared_key = receiver_private_key.exchange(ec.ECDH(), sender_public_key)
    iv = '000000000000'
    xkdf = x963kdf.X963KDF(
        algorithm = hashes.SHA256(),
        length = 32,
        sharedinfo = '',
        backend = backend
        )
    key = xkdf.derive(shared_key)
    decryptor = Cipher(
        algorithms.AES(key),
        modes.GCM(iv,tag),
        backend = backend
        ).decryptor()
    message = decryptor.update(ciphertext) +  decryptor.finalize()
    return message 
Example #11
Source File: encrypted_queries_tools.py    From github-token with GNU General Public License v3.0 6 votes vote down vote up
def encrypt(message, receiver_public_key):
    sender_private_key = ec.generate_private_key(ec.SECP256K1(), backend)
    shared_key = sender_private_key.exchange(ec.ECDH(), receiver_public_key)
    sender_public_key = sender_private_key.public_key()
    point = sender_public_key.public_numbers().encode_point()
    iv = '000000000000'
    xkdf = x963kdf.X963KDF(
        algorithm = hashes.SHA256(),
        length = 32,
        sharedinfo = '',
        backend = backend
        )
    key = xkdf.derive(shared_key)
    encryptor = Cipher(
        algorithms.AES(key),
        modes.GCM(iv),
        backend = backend
        ).encryptor()
    ciphertext = encryptor.update(message) + encryptor.finalize()
    return point + encryptor.tag + ciphertext 
Example #12
Source File: enc_basic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def decrypt(self, shared_key, ciphertext):
		# the nonce should be 16 bytes long random data, but because of the 
		# small message size, we just get 4bytes and use it 4 times (extend).
		# This is ugly, makes the encryption more vulnerable, but if you need
		# something strong, please use the enhanced encryption module.
		nonce = ciphertext[0:4]
		extended_nonce = nonce*4
		algorithm = algorithms.ChaCha20(shared_key, extended_nonce)
		cipher = Cipher(algorithm, mode=None, backend=default_backend())
		decryptor = cipher.decryptor()

		return decryptor.update(ciphertext[4:])

	# server side.
	# Sending the pre-generated public key from the file to the client for 
	# verification purposes + key exchange 
Example #13
Source File: keywrap.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _wrap_core(wrapping_key, a, r, backend):
    # RFC 3394 Key Wrap - 2.2.1 (index method)
    encryptor = Cipher(AES(wrapping_key), ECB(), backend).encryptor()
    n = len(r)
    for j in range(6):
        for i in range(n):
            # every encryption operation is a discrete 16 byte chunk (because
            # AES has a 128-bit block size) and since we're using ECB it is
            # safe to reuse the encryptor for the entire operation
            b = encryptor.update(a + r[i])
            # pack/unpack are safe as these are always 64-bit chunks
            a = struct.pack(
                ">Q", struct.unpack(">Q", b[:8])[0] ^ ((n * j) + i + 1)
            )
            r[i] = b[-8:]

    assert encryptor.finalize() == b""

    return a + b"".join(r) 
Example #14
Source File: keywrap.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _wrap_core(wrapping_key, a, r, backend):
    # RFC 3394 Key Wrap - 2.2.1 (index method)
    encryptor = Cipher(AES(wrapping_key), ECB(), backend).encryptor()
    n = len(r)
    for j in range(6):
        for i in range(n):
            # every encryption operation is a discrete 16 byte chunk (because
            # AES has a 128-bit block size) and since we're using ECB it is
            # safe to reuse the encryptor for the entire operation
            b = encryptor.update(a + r[i])
            # pack/unpack are safe as these are always 64-bit chunks
            a = struct.pack(
                ">Q", struct.unpack(">Q", b[:8])[0] ^ ((n * j) + i + 1)
            )
            r[i] = b[-8:]

    assert encryptor.finalize() == b""

    return a + b"".join(r) 
Example #15
Source File: keywrap.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _wrap_core(wrapping_key, a, r, backend):
    # RFC 3394 Key Wrap - 2.2.1 (index method)
    encryptor = Cipher(AES(wrapping_key), ECB(), backend).encryptor()
    n = len(r)
    for j in range(6):
        for i in range(n):
            # every encryption operation is a discrete 16 byte chunk (because
            # AES has a 128-bit block size) and since we're using ECB it is
            # safe to reuse the encryptor for the entire operation
            b = encryptor.update(a + r[i])
            # pack/unpack are safe as these are always 64-bit chunks
            a = struct.pack(
                ">Q", struct.unpack(">Q", b[:8])[0] ^ ((n * j) + i + 1)
            )
            r[i] = b[-8:]

    assert encryptor.finalize() == b""

    return a + b"".join(r) 
Example #16
Source File: fernet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _encrypt_from_parts(self, data, current_time, iv):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
        )

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac) 
Example #17
Source File: crypto.py    From tattle with Mozilla Public License 2.0 6 votes vote down vote up
def encrypt_data(data, key, version=0):
    """
    Encrypt data using the given key

    :param data: data to encrypt
    :param key: encryption key (should be 120, 192, 256 bits)
    :param version: encryption payload version
    :return: encrypted data (version + nonce + tag + cipher text)
    """
    validate_key(key)

    nonce = _generate_nonce()

    cipher = ciphers.Cipher(algorithms.AES(key), modes.GCM(nonce), backend=backends.default_backend())

    encryptor = cipher.encryptor()

    cipher_text = encryptor.update(data) + encryptor.finalize()

    tag = encryptor.tag

    return struct.pack('>B', version) + nonce + tag + cipher_text 
Example #18
Source File: transport.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _getSupportedCiphers():
    """
    Build a list of ciphers that are supported by the backend in use.

    @return: a list of supported ciphers.
    @rtype: L{list} of L{str}
    """
    supportedCiphers = []
    cs = [b'aes256-ctr', b'aes256-cbc', b'aes192-ctr', b'aes192-cbc',
          b'aes128-ctr', b'aes128-cbc', b'cast128-ctr', b'cast128-cbc',
          b'blowfish-ctr', b'blowfish-cbc', b'3des-ctr', b'3des-cbc']
    for cipher in cs:
        algorithmClass, keySize, modeClass = SSHCiphers.cipherMap[cipher]
        try:
            Cipher(
                algorithmClass(b' ' * keySize),
                modeClass(b' ' * (algorithmClass.block_size // 8)),
                backend=default_backend(),
            ).encryptor()
        except UnsupportedAlgorithm:
            pass
        else:
            supportedCiphers.append(cipher)
    return supportedCiphers 
Example #19
Source File: transport.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _getCipher(self, cip, iv, key):
        """
        Creates an initialized cipher object.

        @param cip: the name of the cipher, maps into cipherMap
        @param iv: the initialzation vector
        @param key: the encryption key

        @return: the cipher object.
        """
        algorithmClass, keySize, modeClass = self.cipherMap[cip]
        if algorithmClass is None:
            return _DummyCipher()

        return Cipher(
            algorithmClass(key[:keySize]),
            modeClass(iv[:algorithmClass.block_size // 8]),
            backend=default_backend(),
        ) 
Example #20
Source File: security.py    From PyZwaver with GNU General Public License v3.0 6 votes vote down vote up
def _CTR_DRBG_AES128_update(data, key, v):
    assert len(data) == 32
    assert len(key) == 16
    assert len(v) == 16
    cipher = Cipher(algorithms.AES(key), modes.CBC(str_zero(16)),
                    backend=default_backend())

    v = str_inc(v)
    encryptor = cipher.encryptor()
    new_key = encryptor.update(v) + encryptor.finalize()

    v = str_inc(v)
    encryptor = cipher.encryptor()
    new_v = encryptor.update(v) + encryptor.finalize()
    return str_xor(new_key, data[:16]), str_xor(new_v, data[16:])


# Counter mode Deterministic Random Byte Generator
# Specialized for SPAN based on NIST 800-90A 
Example #21
Source File: security.py    From PyZwaver with GNU General Public License v3.0 6 votes vote down vote up
def generate(self, count, data=None):
        out = b""
        v = self._v
        key = self._key
        if data is not None:
            key, v = _CTR_DRBG_AES128_update(data, key, v)
        cipher = Cipher(algorithms.AES(key), modes.CBC(str_zero(16)),
                        backend=default_backend())

        while len(out) < count:
            encryptor = cipher.encryptor()
            v = str_inc(v)
            out += encryptor.update(v) + encryptor.finalize()
        if data is None:
            data = str_zero(32)
        self._key, self._v = _CTR_DRBG_AES128_update(data, key, v)
        return out[:count] 
Example #22
Source File: fernet.py    From oss-ftp with MIT License 6 votes vote down vote up
def _encrypt_from_parts(self, data, current_time, iv):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
        )

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac) 
Example #23
Source File: pycookiecheat.py    From pycookiecheat with MIT License 6 votes vote down vote up
def chrome_decrypt(
    encrypted_value: bytes, key: bytes, init_vector: bytes
) -> str:
    """Decrypt Chrome/Chromium's encrypted cookies.

    Args:
        encrypted_value: Encrypted cookie from Chrome/Chromium's cookie file
        key: Key to decrypt encrypted_value
        init_vector: Initialization vector for decrypting encrypted_value
    Returns:
        Decrypted value of encrypted_value

    """
    # Encrypted cookies should be prefixed with 'v10' or 'v11' according to the
    # Chromium code. Strip it off.
    encrypted_value = encrypted_value[3:]

    cipher = Cipher(
        algorithm=AES(key), mode=CBC(init_vector), backend=default_backend()
    )
    decryptor = cipher.decryptor()
    decrypted = decryptor.update(encrypted_value) + decryptor.finalize()

    return clean(decrypted) 
Example #24
Source File: pyevpkdf.py    From vrequest with MIT License 6 votes vote down vote up
def get_encryptor(key, iv=None):
        algoer = algorithms.AES(key) #这里的AES算法(若要换成des算法,这里换成TripleDES,该加密库中,DES 事实上等于 TripleDES 的密钥长度为 64bit 时的加解密)
        cipher = Cipher(algoer, modes.CBC(iv), backend=default_backend()) #这里的CBC模式
        def enc(bitstring):
            padder    = padding.PKCS7(algoer.block_size).padder()
            bitstring = padder.update(bitstring) + padder.finalize()
            encryptor = cipher.encryptor()
            return encryptor.update(bitstring) + encryptor.finalize()
        def dec(bitstring):
            decryptor = cipher.decryptor()
            ddata     = decryptor.update(bitstring) + decryptor.finalize()
            unpadder  = padding.PKCS7(algoer.block_size).unpadder()
            return unpadder.update(ddata) + unpadder.finalize()
        class f:pass
        f.encrypt = enc
        f.decrypt = dec
        return f 
Example #25
Source File: crypto.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def aes_cbc_decrypt(key, iv, enc_data):
    """
    Decrypts the given cipherdata with AES (CBC Mode) using the key/iv.

    Attention: This function returns the decrypted data as is, without removing
    any padding. The calling function must take care of this!

    :param key: The encryption key
    :type key: bytes
    :param iv: The initialization vector
    :type iv: bytes
    :param enc_data: The cipher text
    :type enc_data: binary string
    :param mode: The AES MODE
    :return: plain text in binary data
    :rtype: bytes
    """
    backend = default_backend()
    mode = modes.CBC(iv)
    cipher = Cipher(algorithms.AES(key), mode=mode, backend=backend)
    decryptor = cipher.decryptor()
    output = decryptor.update(enc_data) + decryptor.finalize()
    return output 
Example #26
Source File: crypto.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def aes_cbc_encrypt(key, iv, data):
    """
    encrypts the given data with AES (CBC Mode) using key/iv.

    Attention: This function expects correctly padded input data (multiple of
    AES block size). The calling function must take care of this!

    :param key: The encryption key
    :type key: binary string
    :param iv: The initialization vector
    :type iv: binary string
    :param data: The cipher text
    :type data: bytes
    :param mode: The AES MODE
    :return: plain text in binary data
    :rtype: bytes
    """
    assert len(data) % (algorithms.AES.block_size // 8) == 0
    # do the encryption
    backend = default_backend()
    mode = modes.CBC(iv)
    cipher = Cipher(algorithms.AES(key), mode=mode, backend=backend)
    encryptor = cipher.encryptor()
    output = encryptor.update(data) + encryptor.finalize()
    return output 
Example #27
Source File: importotp.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def _create_static_password(key_hex):
    '''
    According to yubikey manual 5.5.5 the static-ticket is the same
    algorithm with no moving factors.
    The msg_hex that is encoded with the AES key is
    '000000000000ffffffffffffffff0f2e'
    '''
    msg_hex = "000000000000ffffffffffffffff0f2e"
    msg_bin = binascii.unhexlify(msg_hex)
    cipher = Cipher(algorithms.AES(binascii.unhexlify(key_hex)),
                    modes.ECB(), default_backend())
    encryptor = cipher.encryptor()
    password_bin = encryptor.update(msg_bin) + encryptor.finalize()
    password = modhex_encode(password_bin)

    return password 
Example #28
Source File: rc4.py    From msoffcrypto-tool with MIT License 6 votes vote down vote up
def verifypw(password, salt, encryptedVerifier, encryptedVerifierHash):
        r'''
        Return True if the given password is valid.

            >>> password = 'password1'
            >>> salt = b'\xe8w,\x1d\x91\xc5j7\x96Ga\xb2\x80\x182\x17'
            >>> encryptedVerifier = b'\xc9\xe9\x97\xd4T\x97=1\x0b\xb1\xbap\x14&\x83~'
            >>> encryptedVerifierHash = b'\xb1\xde\x17\x8f\x07\xe9\x89\xc4M\xae^L\xf9j\xc4\x07'
            >>> DocumentRC4.verifypw(password, salt, encryptedVerifier, encryptedVerifierHash)
            True
        '''
        # https://msdn.microsoft.com/en-us/library/dd952648(v=office.12).aspx
        block = 0
        key = _makekey(password, salt, block)
        cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend())
        decryptor = cipher.decryptor()
        verifier = decryptor.update(encryptedVerifier)
        verfiferHash = decryptor.update(encryptedVerifierHash)
        hash = md5(verifier).digest()
        logging.debug([verfiferHash, hash])
        return hash == verfiferHash 
Example #29
Source File: rc4.py    From msoffcrypto-tool with MIT License 6 votes vote down vote up
def decrypt(password, salt, ibuf, blocksize=0x200):
        r'''
        Return decrypted data.
        '''
        obuf = io.BytesIO()

        block = 0
        key = _makekey(password, salt, block)

        for c, buf in enumerate(iter(functools.partial(ibuf.read, blocksize), b'')):
            cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend())
            decryptor = cipher.decryptor()

            dec = decryptor.update(buf) + decryptor.finalize()
            obuf.write(dec)

            # From wvDecrypt:
            # at this stage we need to rekey the rc4 algorithm
            # Dieter Spaar <spaar@mirider.augusta.de> figured out
            # this rekeying, big kudos to him
            block += 1
            key = _makekey(password, salt, block)

        obuf.seek(0)
        return obuf 
Example #30
Source File: ecma376_standard.py    From msoffcrypto-tool with MIT License 6 votes vote down vote up
def verifykey(key, encryptedVerifier, encryptedVerifierHash):
        r'''
        Return True if the given intermediate key is valid.

            >>> key = b'@\xb1:q\xf9\x0b\x96n7T\x08\xf2\xd1\x81\xa1\xaa'
            >>> encryptedVerifier = b'Qos.\x96o\xac\x17\xb1\xc5\xd7\xd8\xcc6\xc9('
            >>> encryptedVerifierHash = b'+ah\xda\xbe)\x11\xad+\xd3|\x17Ft\\\x14\xd3\xcf\x1b\xb1@\xa4\x8fNo=#\x88\x08r\xb1j'
            >>> ECMA376Standard.verifykey(key, encryptedVerifier, encryptedVerifierHash)
            True
        '''
        # TODO: For consistency with Agile, rename method to verify_password or the like
        logger.debug([key, encryptedVerifier, encryptedVerifierHash])
        # https://msdn.microsoft.com/en-us/library/dd926426(v=office.12).aspx
        aes = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
        decryptor = aes.decryptor()
        verifier = decryptor.update(encryptedVerifier)
        expected_hash = sha1(verifier).digest()
        decryptor = aes.decryptor()
        verifierHash = decryptor.update(encryptedVerifierHash)[:sha1().digest_size]
        return expected_hash == verifierHash