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


Python modes.CTR屬性代碼示例

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


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

示例1: _layer_cipher

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [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

示例2: __init__

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def __init__(self, key, mode = cipherMODE.ECB, IV = None, pad = None, padMode = None):
		self.IV = IV
		#the python cryptography module sets the IV in the operational mode!!!
		if mode == cipherMODE.ECB:
			self.IV = modes.ECB()
		elif mode == cipherMODE.CBC:
			self.IV = modes.CBC(IV)
		elif mode == cipherMODE.CBC:
			self.IV = modes.CTR(IV)
		else:
			raise Exception('Unknown cipher mode!')
		
		self.key = key
		
		""" TODO padding
		if self.padMode is not None:
		"""
		
		self.encryptor = None
		self.decryptor = None
		symmetricBASE.__init__(self) 
開發者ID:skelsec,項目名稱:msldap,代碼行數:23,代碼來源:AES.py

示例3: verify2

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def verify2(self, atv_public_key, data):
        """Last device verification step."""
        self._check_initialized()
        log_binary(_LOGGER, "Verify", PublicSecret=atv_public_key, Data=data)

        # Generate a shared secret key
        shared = self._verify_private.exchange(
            X25519PublicKey.from_public_bytes(atv_public_key)
        )
        log_binary(_LOGGER, "Shared secret", Secret=shared)

        # Derive new AES key and IV from shared key
        aes_key = hash_sha512("Pair-Verify-AES-Key", shared)[0:16]
        aes_iv = hash_sha512("Pair-Verify-AES-IV", shared)[0:16]
        log_binary(_LOGGER, "Pair-Verify-AES", Key=aes_key, IV=aes_iv)

        # Sign public keys and encrypt with AES
        signer = Ed25519PrivateKey.from_private_bytes(self._auth_private)
        signed = signer.sign(self._public_bytes + atv_public_key)
        signature, _ = aes_encrypt(modes.CTR, aes_key, aes_iv, data, signed)
        log_binary(_LOGGER, "Signature", Signature=signature)

        # Signature is prepended with 0x00000000 (alignment?)
        return b"\x00\x00\x00\x00" + signature 
開發者ID:postlund,項目名稱:pyatv,代碼行數:26,代碼來源:srp.py

示例4: update

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def update(self, data):
        ret = b""
        if self.cipher is None:
            key = os.urandom(16)
            nonce = os.urandom(16)
            auth_key = os.urandom(32)
            self.cipher = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=default_backend()).encryptor()
            self.authenticator = HMAC(auth_key, SHA256(), backend=default_backend())
            pad = padding.OAEP(mgf=padding.MGF1(algorithm=SHA1()),
                               algorithm=SHA1(),
                               label=None)
            cipherkey = self.rsa_public_key.encrypt(key + nonce + auth_key, pad)
            ret = FILEMAGIC + struct.pack(">H", len(cipherkey)) + cipherkey
        cur = self.cipher.update(data)
        self.authenticator.update(cur)
        if ret:
            return ret + cur
        else:
            return cur 
開發者ID:aiven,項目名稱:pghoard,代碼行數:21,代碼來源:encryptor.py

示例5: process_header

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def process_header(self, data):
        if self._cipher_key_len is None:
            if data[0:6] != FILEMAGIC:
                raise EncryptorError("Invalid magic bytes")
            self._cipher_key_len = struct.unpack(">H", data[6:8])[0]
        else:
            pad = padding.OAEP(mgf=padding.MGF1(algorithm=SHA1()),
                               algorithm=SHA1(),
                               label=None)
            try:
                plainkey = self.rsa_private_key.decrypt(data, pad)
            except AssertionError:
                raise EncryptorError("Decrypting key data failed")
            if len(plainkey) != 64:
                raise EncryptorError("Integrity check failed")
            key = plainkey[0:16]
            nonce = plainkey[16:32]
            auth_key = plainkey[32:64]
            self._header_size = 8 + len(data)

            self.cipher = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=default_backend()).decryptor()
            self.authenticator = HMAC(auth_key, SHA256(), backend=default_backend()) 
開發者ID:aiven,項目名稱:pghoard,代碼行數:24,代碼來源:encryptor.py

示例6: tape_gen

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def tape_gen(self, data):
        """Return a bit string, generated from the given data string"""

        # FIXME
        data = str(data).encode()

        # Derive a key from data
        hmac_obj = hmac.HMAC(self.key, digestmod=hashlib.sha256)
        hmac_obj.update(data)
        assert hmac_obj.digest_size == 32
        digest = hmac_obj.digest()

        # Use AES in the CTR mode to generate a pseudo-random bit string
        aes_algo = algorithms.AES(digest)
        aes_cipher = Cipher(aes_algo, mode=CTR(b'\x00' * 16), backend=default_backend())
        encryptor = aes_cipher.encryptor()

        while True:
            encrypted_bytes = encryptor.update(b'\x00' * 16)
            # Convert the data to a list of bits
            bits = util.str_to_bitstring(encrypted_bytes)
            for bit in bits:
                yield bit 
開發者ID:tonyo,項目名稱:pyope,代碼行數:25,代碼來源:ope.py

示例7: __init__

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def __init__(self, relay: 'stem.client.Relay', circ_id: int, kdf: 'stem.client.datatype.KDF') -> None:
    try:
      from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
      from cryptography.hazmat.backends import default_backend
    except ImportError:
      raise ImportError('Circuit construction requires the cryptography module')

    ctr = modes.CTR(ZERO * (algorithms.AES.block_size // 8))  # type: ignore

    self.relay = relay
    self.id = circ_id
    self.forward_digest = hashlib.sha1(kdf.forward_digest)
    self.backward_digest = hashlib.sha1(kdf.backward_digest)
    self.forward_key = Cipher(algorithms.AES(kdf.forward_key), ctr, default_backend()).encryptor()
    self.backward_key = Cipher(algorithms.AES(kdf.backward_key), ctr, default_backend()).decryptor() 
開發者ID:torproject,項目名稱:stem,代碼行數:17,代碼來源:__init__.py

示例8: _decrypt_stealth_auth

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def _decrypt_stealth_auth(content: bytes, authentication_cookie: bytes) -> bytes:
    try:
      from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
      from cryptography.hazmat.backends import default_backend
    except ImportError:
      raise DecryptionFailure('Decrypting introduction-points requires the cryptography module')

    # byte 1 = authentication type, 2-17 = input vector, 18 on = encrypted content
    iv, encrypted = content[1:17], content[17:]
    cipher = Cipher(algorithms.AES(authentication_cookie), modes.CTR(iv), default_backend())
    decryptor = cipher.decryptor()

    return decryptor.update(encrypted) + decryptor.finalize() 
開發者ID:torproject,項目名稱:stem,代碼行數:15,代碼來源:hidden_service.py

示例9: _open_aes_ctr

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def _open_aes_ctr(key, nonce, ciphertext, expected_hmac, digest_method):
    data_key, hmac_key = _halve_key(key)
    hmac = _get_hmac(hmac_key, ciphertext, digest_method)
    # Check the HMAC before we decrypt to verify ciphertext integrity
    if not constant_time.bytes_eq(hmac, expected_hmac):
        raise IntegrityError("Computed HMAC on %s does not match stored HMAC")

    decryptor = Cipher(
        algorithms.AES(data_key),
        modes.CTR(nonce),
        backend=default_backend()
    ).decryptor()
    return decryptor.update(ciphertext) + decryptor.finalize() 
開發者ID:fugue,項目名稱:credstash,代碼行數:15,代碼來源:credstash.py

示例10: _seal_aes_ctr

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def _seal_aes_ctr(plaintext, key, nonce, digest_method):
    data_key, hmac_key = _halve_key(key)
    encryptor = Cipher(
        algorithms.AES(data_key),
        modes.CTR(nonce),
        backend=default_backend()
    ).encryptor()

    ciphertext = encryptor.update(plaintext.encode("utf-8")) + encryptor.finalize()
    return ciphertext, _get_hmac(hmac_key, ciphertext, digest_method) 
開發者ID:fugue,項目名稱:credstash,代碼行數:12,代碼來源:credstash.py

示例11: try_use_cryptography_module

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def try_use_cryptography_module():
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from cryptography.hazmat.backends import default_backend

    class CryptographyEncryptorAdapter:
        __slots__ = ('encryptor', 'decryptor')

        def __init__(self, cipher):
            self.encryptor = cipher.encryptor()
            self.decryptor = cipher.decryptor()

        def encrypt(self, data):
            return self.encryptor.update(data)

        def decrypt(self, data):
            return self.decryptor.update(data)

    def create_aes_ctr(key, iv):
        iv_bytes = int.to_bytes(iv, 16, "big")
        cipher = Cipher(algorithms.AES(key), modes.CTR(iv_bytes), default_backend())
        return CryptographyEncryptorAdapter(cipher)

    def create_aes_cbc(key, iv):
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv), default_backend())
        return CryptographyEncryptorAdapter(cipher)

    return create_aes_ctr, create_aes_cbc 
開發者ID:alexbers,項目名稱:mtprotoproxy,代碼行數:29,代碼來源:mtprotoproxy.py

示例12: initCipher

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def initCipher(self, nonce, encryptor=False, decryptor=False):
        assert not (encryptor and decryptor)
        cipher = Cipher(algorithms.AES(config.key), modes.CTR(nonce), default_backend())
        if encryptor:
            enc = cipher.encryptor()
            self.encrypt = lambda dat: enc.update(dat)
        elif decryptor:
            dec = cipher.decryptor()
            self.decrypt = lambda dat: dec.update(dat) 
開發者ID:krrr,項目名稱:wstan,代碼行數:11,代碼來源:relay.py

示例13: encrypt

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def encrypt(self, relay_payload):
        cipher = Cipher(AES(self.encryption_key), CTR(b'\x00' * 16), backend=default_backend()).encryptor()
        return cipher.update(relay_payload) 
開發者ID:Marten4n6,項目名稱:TinyTor,代碼行數:5,代碼來源:tinytor.py

示例14: decrypt

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def decrypt(self, relay_payload):
        cipher = Cipher(AES(self.decryption_key), CTR(b'\x00' * 16), backend=default_backend()).decryptor()
        return cipher.update(relay_payload) 
開發者ID:Marten4n6,項目名稱:TinyTor,代碼行數:5,代碼來源:tinytor.py

示例15: setup_cipher

# 需要導入模塊: from cryptography.hazmat.primitives.ciphers import modes [as 別名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import CTR [as 別名]
def setup_cipher(self):
		if self.mode == cipherMODE.ECB:
			self._cipher = AESModeOfOperationECB(self.key)
		elif self.mode == cipherMODE.CBC:
			self._cipher = AESModeOfOperationCBC(self.key, iv = self.IV)
		elif self.mode == cipherMODE.CTR:
			self._cipher = AESModeOfOperationCTR(self.key, iv = self.IV)
		else:
			raise Exception('Unknown cipher mode!') 
開發者ID:skelsec,項目名稱:msldap,代碼行數:11,代碼來源:AES.py


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