当前位置: 首页>>代码示例>>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;未经允许,请勿转载。