当前位置: 首页>>代码示例>>Python>>正文


Python modes.GCM属性代码示例

本文整理汇总了Python中cryptography.hazmat.primitives.ciphers.modes.GCM属性的典型用法代码示例。如果您正苦于以下问题:Python modes.GCM属性的具体用法?Python modes.GCM怎么用?Python modes.GCM使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在cryptography.hazmat.primitives.ciphers.modes的用法示例。


在下文中一共展示了modes.GCM属性的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: encrypt

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [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

示例2: decrypt

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [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

示例3: unwrap

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [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

示例4: encrypt

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [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

示例5: decrypt

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def decrypt(self, k, a, iv, e, t):
        """ Decrypt accoriding 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
        """
        cipher = Cipher(algorithms.AES(k), modes.GCM(iv, t),
                        backend=self.backend)
        decryptor = cipher.decryptor()
        decryptor.authenticate_additional_data(a)
        return decryptor.update(e) + decryptor.finalize() 
开发者ID:latchset,项目名称:jwcrypto,代码行数:18,代码来源:jwa.py

示例6: encrypt_data

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [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

示例7: update

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def update(self, data):
        # OpenSSL 0.9.8e has an assertion in its EVP code that causes it
        # to SIGABRT if you call update with an empty byte string. This can be
        # removed when we drop support for 0.9.8e (CentOS/RHEL 5). This branch
        # should be taken only when length is zero and mode is not GCM because
        # AES GCM can return improper tag values if you don't call update
        # with empty plaintext when authenticating AAD for ...reasons.
        if len(data) == 0 and not isinstance(self._mode, modes.GCM):
            return b""

        buf = self._backend._ffi.new("unsigned char[]",
                                     len(data) + self._block_size - 1)
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherUpdate(self._ctx, buf, outlen, data,
                                                  len(data))
        self._backend.openssl_assert(res != 0)
        return self._backend._ffi.buffer(buf)[:outlen[0]] 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:19,代码来源:ciphers.py

示例8: step3

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def step3(self):
        """Last authentication step."""
        self._check_initialized()
        session_key = binascii.unhexlify(self.session.key)

        aes_key = hash_sha512("Pair-Setup-AES-Key", session_key)[0:16]
        tmp = bytearray(hash_sha512("Pair-Setup-AES-IV", session_key)[0:16])
        _LOGGER.debug("Increase last byte from %d to %s", tmp[-1], tmp[-1] + 1)
        tmp[-1] = tmp[-1] + 1  # Last byte must be increased by 1
        aes_iv = bytes(tmp)
        log_binary(_LOGGER, "Pair-Setup-AES", Key=aes_key, IV=aes_iv)

        epk, tag = aes_encrypt(modes.GCM, aes_key, aes_iv, self._auth_public)
        log_binary(_LOGGER, "Pair-Setup EPK+Tag", EPK=epk, Tag=tag)

        return epk, tag 
开发者ID:postlund,项目名称:pyatv,代码行数:18,代码来源:srp.py

示例9: wrap

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def wrap(self, key, bitsize, cek, headers):
        rk = self._get_key(key, 'encrypt')
        if not cek:
            cek = _randombits(bitsize)

        iv = _randombits(96)
        cipher = Cipher(algorithms.AES(rk), modes.GCM(iv),
                        backend=self.backend)
        encryptor = cipher.encryptor()
        ek = encryptor.update(cek) + encryptor.finalize()

        tag = encryptor.tag
        return {'cek': cek, 'ek': ek,
                'header': {'iv': base64url_encode(iv),
                           'tag': base64url_encode(tag)}} 
开发者ID:latchset,项目名称:jwcrypto,代码行数:17,代码来源:jwa.py

示例10: decrypt_data

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def decrypt_data(raw, keys=None):
    """
    Decrypt data using the given keys

    :param raw: data to decrypt
    :param keys: list of encryption keys
    :return:
    """
    offset = 0
    version, = struct.unpack('>B', raw[0:VER_SIZE])
    offset += VER_SIZE

    nonce = raw[offset:offset + IV_SIZE]
    offset += IV_SIZE

    tag = raw[offset:offset + TAG_SIZE]
    offset += TAG_SIZE

    cipher_text = raw[offset:]

    for key in keys:
        validate_key(key)

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

        decryptor = cipher.decryptor()

        try:
            plain_text = decryptor.update(cipher_text) + decryptor.finalize()
        except (exceptions.InvalidTag, exceptions.InvalidKey):
            continue

        return plain_text

    raise DecryptError("Failed to decrypt data") 
开发者ID:kippandrew,项目名称:tattle,代码行数:37,代码来源:crypto.py

示例11: finalize

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def finalize(self):
        # OpenSSL 1.0.1 on Ubuntu 12.04 (and possibly other distributions)
        # appears to have a bug where you must make at least one call to update
        # even if you are only using authenticate_additional_data or the
        # GCM tag will be wrong. An (empty) call to update resolves this
        # and is harmless for all other versions of OpenSSL.
        if isinstance(self._mode, modes.GCM):
            self.update(b"")

        buf = self._backend._ffi.new("unsigned char[]", self._block_size)
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
        if res == 0:
            errors = self._backend._consume_errors()

            if not errors and isinstance(self._mode, modes.GCM):
                raise InvalidTag

            self._backend.openssl_assert(
                errors[0][1:] == (
                    self._backend._lib.ERR_LIB_EVP,
                    self._backend._lib.EVP_F_EVP_ENCRYPTFINAL_EX,
                    self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
                ) or errors[0][1:] == (
                    self._backend._lib.ERR_LIB_EVP,
                    self._backend._lib.EVP_F_EVP_DECRYPTFINAL_EX,
                    self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
                )
            )
            raise ValueError(
                "The length of the provided data is not a multiple of "
                "the block length."
            )

        if (isinstance(self._mode, modes.GCM) and
           self._operation == self._ENCRYPT):
            block_byte_size = self._block_size // 8
            tag_buf = self._backend._ffi.new(
                "unsigned char[]", block_byte_size
            )
            res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
                self._ctx, self._backend._lib.EVP_CTRL_GCM_GET_TAG,
                block_byte_size, tag_buf
            )
            self._backend.openssl_assert(res != 0)
            self._tag = self._backend._ffi.buffer(tag_buf)[:]

        res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
        self._backend.openssl_assert(res == 1)
        return self._backend._ffi.buffer(buf)[:outlen[0]] 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:52,代码来源:ciphers.py

示例12: finalize

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def finalize(self):
        # OpenSSL 1.0.1 on Ubuntu 12.04 (and possibly other distributions)
        # appears to have a bug where you must make at least one call to update
        # even if you are only using authenticate_additional_data or the
        # GCM tag will be wrong. An (empty) call to update resolves this
        # and is harmless for all other versions of OpenSSL.
        if isinstance(self._mode, modes.GCM):
            self.update(b"")

        buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes)
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
        if res == 0:
            errors = self._backend._consume_errors()

            if not errors and isinstance(self._mode, modes.GCM):
                raise InvalidTag

            self._backend.openssl_assert(
                errors[0][1:] == (
                    self._backend._lib.ERR_LIB_EVP,
                    self._backend._lib.EVP_F_EVP_ENCRYPTFINAL_EX,
                    self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
                ) or errors[0][1:] == (
                    self._backend._lib.ERR_LIB_EVP,
                    self._backend._lib.EVP_F_EVP_DECRYPTFINAL_EX,
                    self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
                )
            )
            raise ValueError(
                "The length of the provided data is not a multiple of "
                "the block length."
            )

        if (isinstance(self._mode, modes.GCM) and
           self._operation == self._ENCRYPT):
            tag_buf = self._backend._ffi.new(
                "unsigned char[]", self._block_size_bytes
            )
            res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
                self._ctx, self._backend._lib.EVP_CTRL_GCM_GET_TAG,
                self._block_size_bytes, tag_buf
            )
            self._backend.openssl_assert(res != 0)
            self._tag = self._backend._ffi.buffer(tag_buf)[:]

        res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
        self._backend.openssl_assert(res == 1)
        return self._backend._ffi.buffer(buf)[:outlen[0]] 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:51,代码来源:ciphers.py

示例13: finalize

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def finalize(self):
        # OpenSSL 1.0.1 on Ubuntu 12.04 (and possibly other distributions)
        # appears to have a bug where you must make at least one call to update
        # even if you are only using authenticate_additional_data or the
        # GCM tag will be wrong. An (empty) call to update resolves this
        # and is harmless for all other versions of OpenSSL.
        if isinstance(self._mode, modes.GCM):
            self.update(b"")

        if (
            self._operation == self._DECRYPT and
            isinstance(self._mode, modes.ModeWithAuthenticationTag) and
            self.tag is None
        ):
            raise ValueError(
                "Authentication tag must be provided when decrypting."
            )

        buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes)
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
        if res == 0:
            errors = self._backend._consume_errors()

            if not errors and isinstance(self._mode, modes.GCM):
                raise InvalidTag

            self._backend.openssl_assert(
                errors[0]._lib_reason_match(
                    self._backend._lib.ERR_LIB_EVP,
                    self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
                )
            )
            raise ValueError(
                "The length of the provided data is not a multiple of "
                "the block length."
            )

        if (isinstance(self._mode, modes.GCM) and
           self._operation == self._ENCRYPT):
            tag_buf = self._backend._ffi.new(
                "unsigned char[]", self._block_size_bytes
            )
            res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
                self._ctx, self._backend._lib.EVP_CTRL_AEAD_GET_TAG,
                self._block_size_bytes, tag_buf
            )
            self._backend.openssl_assert(res != 0)
            self._tag = self._backend._ffi.buffer(tag_buf)[:]

        res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
        self._backend.openssl_assert(res == 1)
        return self._backend._ffi.buffer(buf)[:outlen[0]] 
开发者ID:tp4a,项目名称:teleport,代码行数:55,代码来源:ciphers.py

示例14: finalize

# 需要导入模块: from cryptography.hazmat.primitives.ciphers import modes [as 别名]
# 或者: from cryptography.hazmat.primitives.ciphers.modes import GCM [as 别名]
def finalize(self):
        # OpenSSL 1.0.1 on Ubuntu 12.04 (and possibly other distributions)
        # appears to have a bug where you must make at least one call to update
        # even if you are only using authenticate_additional_data or the
        # GCM tag will be wrong. An (empty) call to update resolves this
        # and is harmless for all other versions of OpenSSL.
        if isinstance(self._mode, modes.GCM):
            self.update(b"")

        if (
            self._operation == self._DECRYPT and
            isinstance(self._mode, modes.ModeWithAuthenticationTag) and
            self.tag is None
        ):
            raise ValueError(
                "Authentication tag must be provided when decrypting."
            )

        buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes)
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
        if res == 0:
            errors = self._backend._consume_errors()

            if not errors and isinstance(self._mode, modes.GCM):
                raise InvalidTag

            self._backend.openssl_assert(
                errors[0]._lib_reason_match(
                    self._backend._lib.ERR_LIB_EVP,
                    self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
                ) or errors[0]._lib_reason_match(
                    self._backend._lib.ERR_LIB_EVP,
                    self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
                )
            )
            raise ValueError(
                "The length of the provided data is not a multiple of "
                "the block length."
            )

        if (isinstance(self._mode, modes.GCM) and
           self._operation == self._ENCRYPT):
            tag_buf = self._backend._ffi.new(
                "unsigned char[]", self._block_size_bytes
            )
            res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
                self._ctx, self._backend._lib.EVP_CTRL_AEAD_GET_TAG,
                self._block_size_bytes, tag_buf
            )
            self._backend.openssl_assert(res != 0)
            self._tag = self._backend._ffi.buffer(tag_buf)[:]

        res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
        self._backend.openssl_assert(res == 1)
        return self._backend._ffi.buffer(buf)[:outlen[0]] 
开发者ID:aws-quickstart,项目名称:quickstart-git2s3,代码行数:58,代码来源:ciphers.py


注:本文中的cryptography.hazmat.primitives.ciphers.modes.GCM属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。