當前位置: 首頁>>代碼示例>>Python>>正文


Python ciphers.Cipher方法代碼示例

本文整理匯總了Python中cryptography.hazmat.primitives.ciphers.Cipher方法的典型用法代碼示例。如果您正苦於以下問題:Python ciphers.Cipher方法的具體用法?Python ciphers.Cipher怎麽用?Python ciphers.Cipher使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cryptography.hazmat.primitives.ciphers的用法示例。


在下文中一共展示了ciphers.Cipher方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: decrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:18,代碼來源:enc_basic.py

示例2: encrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:ethereans,項目名稱:github-token,代碼行數:22,代碼來源:encrypted_queries_tools.py

示例3: decrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:ethereans,項目名稱:github-token,代碼行數:24,代碼來源:encrypted_queries_tools.py

示例4: unwrap

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:latchset,項目名稱:jwcrypto,代碼行數:19,代碼來源:jwa.py

示例5: decrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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() 
開發者ID:latchset,項目名稱:jwcrypto,代碼行數:27,代碼來源:jwa.py

示例6: encrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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) 
開發者ID:latchset,項目名稱:jwcrypto,代碼行數:20,代碼來源:jwa.py

示例7: _layer_cipher

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
def _layer_cipher(constant: bytes, revision_counter: int, subcredential: bytes, blinded_key: bytes, salt: bytes) -> Tuple['cryptography.hazmat.primitives.ciphers.Cipher', Callable[[bytes], bytes]]:  # type: ignore
  try:
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from cryptography.hazmat.backends import default_backend
  except ImportError:
    raise ImportError('Layer encryption/decryption requires the cryptography module')

  kdf = hashlib.shake_256(blinded_key + subcredential + struct.pack('>Q', revision_counter) + salt + constant)
  keys = kdf.digest(S_KEY_LEN + S_IV_LEN + MAC_LEN)

  secret_key = keys[:S_KEY_LEN]
  secret_iv = keys[S_KEY_LEN:S_KEY_LEN + S_IV_LEN]
  mac_key = keys[S_KEY_LEN + S_IV_LEN:]

  cipher = Cipher(algorithms.AES(secret_key), modes.CTR(secret_iv), default_backend())
  mac_prefix = struct.pack('>Q', len(mac_key)) + mac_key + struct.pack('>Q', len(salt)) + salt

  return cipher, lambda ciphertext: hashlib.sha3_256(mac_prefix + ciphertext).digest() 
開發者ID:torproject,項目名稱:stem,代碼行數:20,代碼來源:hidden_service.py

示例8: encrypt_data

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:kippandrew,項目名稱:tattle,代碼行數:24,代碼來源:crypto.py

示例9: _CTR_DRBG_AES128_update

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:robertmuth,項目名稱:PyZwaver,代碼行數:21,代碼來源:security.py

示例10: generate

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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] 
開發者ID:robertmuth,項目名稱:PyZwaver,代碼行數:19,代碼來源:security.py

示例11: aes_cbc_decrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:25,代碼來源:crypto.py

示例12: aes_cbc_encrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:27,代碼來源:crypto.py

示例13: _create_static_password

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:18,代碼來源:importotp.py

示例14: verifypw

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:nolze,項目名稱:msoffcrypto-tool,代碼行數:23,代碼來源:rc4.py

示例15: decrypt

# 需要導入模塊: from cryptography.hazmat.primitives import ciphers [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers import Cipher [as 別名]
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 
開發者ID:nolze,項目名稱:msoffcrypto-tool,代碼行數:27,代碼來源:rc4.py


注:本文中的cryptography.hazmat.primitives.ciphers.Cipher方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。