Python cryptography.hazmat.primitives.padding.PKCS7 Examples
The following are 30
code examples of cryptography.hazmat.primitives.padding.PKCS7().
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.padding
, or try the search function
.
Example #1
Source File: crypto.py From privacyidea with GNU Affero General Public License v3.0 | 7 votes |
def aes_encrypt_b64(key, data): """ This function encrypts the data using AES-128-CBC. It generates and adds an IV. This is used for PSKC. :param key: Encryption key (binary format) :type key: bytes :param data: Data to encrypt :type data: bytes :return: base64 encrypted output, containing IV and encrypted data :rtype: str """ # pad data padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_data = padder.update(data) + padder.finalize() iv = geturandom(16) encdata = aes_cbc_encrypt(key, iv, padded_data) return b64encode_and_unicode(iv + encdata)
Example #2
Source File: crypto.py From privacyidea with GNU Affero General Public License v3.0 | 7 votes |
def aes_decrypt_b64(key, enc_data_b64): """ This function decrypts base64 encoded data (containing the IV) using AES-128-CBC. Used for PSKC :param key: binary key :param enc_data_b64: base64 encoded data (IV + encdata) :type enc_data_b64: str :return: encrypted data """ data_bin = base64.b64decode(enc_data_b64) iv = data_bin[:16] encdata = data_bin[16:] padded_data = aes_cbc_decrypt(key, iv, encdata) # remove padding unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() output = unpadder.update(padded_data) + unpadder.finalize() return output # @log_with(log)
Example #3
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 6 votes |
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 #4
Source File: serializer.py From pypsrp with MIT License | 6 votes |
def _serialize_secure_string(self, value): if self.cipher is None: raise SerializationError("Cannot generate secure string as cipher " "is not initialised") # convert the string to a UTF-16 byte string as that is what is # expected in Windows. If a byte string (native string in Python 2) was # passed in, the sender must make sure it is a valid UTF-16 # representation and not UTF-8 or else the server will fail to decrypt # the secure string in most cases string_bytes = to_bytes(value, encoding='utf-16-le') padder = PKCS7(self.cipher.algorithm.block_size).padder() padded_data = padder.update(string_bytes) + padder.finalize() encryptor = self.cipher.encryptor() ss_value = encryptor.update(padded_data) + encryptor.finalize() ss_string = to_string(base64.b64encode(ss_value)) return ss_string
Example #5
Source File: test_blob_encryption.py From azure-storage-python with MIT License | 6 votes |
def test_validate_encryption(self): # Arrange self.bbs.require_encryption = True kek = KeyWrapper('key1') self.bbs.key_encryption_key = kek blob_name = self._create_small_blob('block_blob') # Act self.bbs.require_encryption = False self.bbs.key_encryption_key = None blob = self.bbs.get_blob_to_bytes(self.container_name, blob_name) encryption_data = _dict_to_encryption_data(loads(blob.metadata['encryptiondata'])) iv = encryption_data.content_encryption_IV content_encryption_key = _validate_and_unwrap_cek(encryption_data, kek, None) cipher = _generate_AES_CBC_cipher(content_encryption_key, iv) decryptor = cipher.decryptor() unpadder = PKCS7(128).unpadder() content = decryptor.update(blob.content) + decryptor.finalize() content = unpadder.update(content) + unpadder.finalize() self.assertEqual(self.bytes, content)
Example #6
Source File: fernet.py From quickstart-git2s3 with Apache License 2.0 | 6 votes |
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 #7
Source File: pkcs11.py From barbican with Apache License 2.0 | 6 votes |
def _CKM_AES_CBC_encrypt(self, key, pt_data, session): iv = self._generate_random(_CBC_IV_SIZE, session) ck_mechanism = self._build_cbc_mechanism(iv) rv = self.lib.C_EncryptInit(session, ck_mechanism.mech, key) self._check_error(rv) padder = padding.PKCS7(_CBC_BLOCK_SIZE).padder() padded_pt_data = padder.update(pt_data) padded_pt_data += padder.finalize() pt_len = len(padded_pt_data) ct_len = self.ffi.new("CK_ULONG *", pt_len) ct = self.ffi.new("CK_BYTE[{}]".format(ct_len[0])) rv = self.lib.C_Encrypt(session, padded_pt_data, pt_len, ct, ct_len) self._check_error(rv) return { "iv": self.ffi.buffer(iv)[:], "ct": self.ffi.buffer(ct, ct_len[0])[:] }
Example #8
Source File: fernet.py From teleport with Apache License 2.0 | 6 votes |
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 #9
Source File: pkcs11.py From barbican with Apache License 2.0 | 6 votes |
def _CKM_AES_CBC_decrypt(self, key, iv, ct_data, session): iv = self.ffi.new("CK_BYTE[{}]".format(len(iv)), iv) ck_mechanism = self._build_cbc_mechanism(iv) rv = self.lib.C_DecryptInit(session, ck_mechanism.mech, key) self._check_error(rv) ct_len = len(ct_data) pt_len = self.ffi.new("CK_ULONG *", ct_len) pt = self.ffi.new("CK_BYTE[{0}]".format(pt_len[0])) rv = self.lib.C_Decrypt(session, ct_data, ct_len, pt, pt_len) self._check_error(rv) pt = self.ffi.buffer(pt, pt_len[0])[:] unpadder = padding.PKCS7(_CBC_BLOCK_SIZE).unpadder() unpadded_pt = unpadder.update(pt) unpadded_pt += unpadder.finalize() return unpadded_pt
Example #10
Source File: fernet.py From teleport with Apache License 2.0 | 6 votes |
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 #11
Source File: fernet.py From teleport with Apache License 2.0 | 6 votes |
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 #12
Source File: fernet.py From learn_python3_spider with MIT License | 6 votes |
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 #13
Source File: fernet.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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 #14
Source File: cse.py From aioboto3 with Apache License 2.0 | 6 votes |
def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes: """ Get decryption key for a given S3 object :param key: Base64 decoded version of x-amz-key :param material_description: JSON decoded x-amz-matdesc :return: Raw AES key bytes """ # So it seems when java just calls Cipher.getInstance('AES') it'll default to AES/ECB/PKCS5Padding aesecb = self._cipher.decryptor() padded_result = await self._loop.run_in_executor(None, lambda: (aesecb.update(key) + aesecb.finalize())) unpadder = PKCS7(AES.block_size).unpadder() result = await self._loop.run_in_executor(None, lambda: (unpadder.update(padded_result) + unpadder.finalize())) return result
Example #15
Source File: cse.py From aioboto3 with Apache License 2.0 | 6 votes |
def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]: """ Get encryption key to encrypt an S3 object :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key """ random_bytes = os.urandom(32) padder = PKCS7(AES.block_size).padder() padded_result = await self._loop.run_in_executor( None, lambda: (padder.update(random_bytes) + padder.finalize())) aesecb = self._cipher.encryptor() encrypted_result = await self._loop.run_in_executor( None, lambda: (aesecb.update(padded_result) + aesecb.finalize())) return random_bytes, {}, base64.b64encode(encrypted_result).decode()
Example #16
Source File: fernet.py From quickstart-redhat-openshift with Apache License 2.0 | 6 votes |
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 #17
Source File: mdmcert.py From commandment with MIT License | 6 votes |
def decrypt_mdmcert(response: bytes, decrypt_with: RSAPrivateKeyWithSerialization) -> bytes: """Decrypt a .plist.b64.p7 supplied by mdmcert.download. In order to decrypt this we need to: - decode the payload using unhexlify() - find the private key that corresponded to the request. Args: response (bytes): The still encryped and hex encoded payload decrypt_with (RSAPrivateKeyWithSerialization): The private key that should be used to decrypt the payload. Returns: bytes - the decrypted response """ decoded_payload = unhexlify(response) # try: result = decrypt_smime_content(decoded_payload, decrypt_with) # except ValueError as e: # return abort(400, e) # result = decrypt_with.decrypt( # decoded_payload, # padding.PKCS7(block_size=8) # ) return result
Example #18
Source File: fernet.py From oss-ftp with MIT License | 6 votes |
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 #19
Source File: pyevpkdf.py From vrequest with MIT License | 6 votes |
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 #20
Source File: fields.py From PGPy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def decrypt(self, pk, *args): km = pk.keymaterial if km.oid == EllipticCurveOID.Curve25519: v = x25519.X25519PublicKey.from_public_bytes(self.p.x) s = km.__privkey__().exchange(v) else: # assemble the public component of ephemeral key v v = ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, km.oid.curve()).public_key(default_backend()) # compute s using the inverse of how it was derived during encryption s = km.__privkey__().exchange(ec.ECDH(), v) # derive the wrapping key z = km.kdf.derive_key(s, km.oid, PubKeyAlgorithm.ECDH, pk.fingerprint) # unwrap and unpad m _m = aes_key_unwrap(z, self.c, default_backend()) padder = PKCS7(64).unpadder() return padder.update(_m) + padder.finalize()
Example #21
Source File: certificate.py From calvin-base with Apache License 2.0 | 6 votes |
def _wrap_object_with_symmetric_key(plaintext): import json import base64 from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend #Pad data padder = padding.PKCS7(128).padder() padded_plaintext = padder.update(plaintext) padded_plaintext += padder.finalize() #Generate random symmetric key and intialization vector key = os.urandom(32) iv = os.urandom(16) #Encrypt object backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) encryptor = cipher.encryptor() ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize() wrapped_object= {'ciphertext': base64.b64encode(ciphertext), 'symmetric_key':base64.b64encode(key), 'iv':base64.b64encode(iv)} return wrapped_object
Example #22
Source File: fernet.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #23
Source File: _encryption.py From azure-storage-python with MIT License | 5 votes |
def _get_blob_encryptor_and_padder(cek, iv, should_pad): encryptor = None padder = None if cek is not None and iv is not None: cipher = _generate_AES_CBC_cipher(cek, iv) encryptor = cipher.encryptor() padder = PKCS7(128).padder() if should_pad else None return encryptor, padder
Example #24
Source File: _encryption.py From azure-storage-python with MIT License | 5 votes |
def _encrypt_blob(blob, key_encryption_key): ''' Encrypts the given blob using AES256 in CBC mode with 128 bit padding. Wraps the generated content-encryption-key using the user-provided key-encryption-key (kek). Returns a json-formatted string containing the encryption metadata. This method should only be used when a blob is small enough for single shot upload. Encrypting larger blobs is done as a part of the _upload_blob_chunks method. :param bytes blob: The blob to be encrypted. :param object key_encryption_key: The user-provided key-encryption-key. Must implement the following methods: wrap_key(key)--wraps the specified key using an algorithm of the user's choice. get_key_wrap_algorithm()--returns the algorithm used to wrap the specified symmetric key. get_kid()--returns a string key id for this key-encryption-key. :return: A tuple of json-formatted string containing the encryption metadata and the encrypted blob data. :rtype: (str, bytes) ''' _validate_not_none('blob', blob) _validate_not_none('key_encryption_key', key_encryption_key) _validate_key_encryption_key_wrap(key_encryption_key) # AES256 uses 256 bit (32 byte) keys and always with 16 byte blocks content_encryption_key = urandom(32) initialization_vector = urandom(16) cipher = _generate_AES_CBC_cipher(content_encryption_key, initialization_vector) # PKCS7 with 16 byte blocks ensures compatibility with AES. padder = PKCS7(128).padder() padded_data = padder.update(blob) + padder.finalize() # Encrypt the data. encryptor = cipher.encryptor() encrypted_data = encryptor.update(padded_data) + encryptor.finalize() encryption_data = _generate_encryption_data_dict(key_encryption_key, content_encryption_key, initialization_vector) encryption_data['EncryptionMode'] = 'FullBlob' return dumps(encryption_data), encrypted_data
Example #25
Source File: _encryption.py From azure-storage-python with MIT License | 5 votes |
def _decrypt(message, encryption_data, key_encryption_key=None, resolver=None): ''' Decrypts the given ciphertext using AES256 in CBC mode with 128 bit padding. Unwraps the content-encryption-key using the user-provided or resolved key-encryption-key (kek). Returns the original plaintex. :param str message: The ciphertext to be decrypted. :param _EncryptionData encryption_data: The metadata associated with this ciphertext. :param object key_encryption_key: The user-provided key-encryption-key. Must implement the following methods: unwrap_key(key, algorithm)--returns the unwrapped form of the specified symmetric key using the string-specified algorithm. get_kid()--returns a string key id for this key-encryption-key. :param function resolver(kid): The user-provided key resolver. Uses the kid string to return a key-encryption-key implementing the interface defined above. :return: The decrypted plaintext. :rtype: str ''' _validate_not_none('message', message) content_encryption_key = _validate_and_unwrap_cek(encryption_data, key_encryption_key, resolver) if not (_EncryptionAlgorithm.AES_CBC_256 == encryption_data.encryption_agent.encryption_algorithm): raise ValueError(_ERROR_UNSUPPORTED_ENCRYPTION_ALGORITHM) cipher = _generate_AES_CBC_cipher(content_encryption_key, encryption_data.content_encryption_IV) # decrypt data decrypted_data = message decryptor = cipher.decryptor() decrypted_data = (decryptor.update(decrypted_data) + decryptor.finalize()) # unpad data unpadder = PKCS7(128).unpadder() decrypted_data = (unpadder.update(decrypted_data) + unpadder.finalize()) return decrypted_data
Example #26
Source File: pador.py From PaddingOracleDemos with GNU General Public License v2.0 | 5 votes |
def decrypt(crypted): """Decrypts with AES-128 and removes PKCS#7 padding.""" iv = KEY backend = default_backend() cipher = Cipher(algorithms.AES(KEY), modes.CBC(iv), backend=backend) decryptor = cipher.decryptor() plain = decryptor.update(crypted) unpadder = padding.PKCS7(BLOCK_SIZE).unpadder() unpadded_data = unpadder.update(plain) + unpadder.finalize() return unpadded_data
Example #27
Source File: fernet.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _decrypt_data(self, data, timestamp, ttl): current_time = int(time.time()) if ttl is not None: if timestamp + ttl < current_time: raise InvalidToken if current_time + _MAX_CLOCK_SKEW < timestamp: raise InvalidToken self._verify_signature(data) iv = data[9:25] ciphertext = data[25:-32] decryptor = Cipher( algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend ).decryptor() plaintext_padded = decryptor.update(ciphertext) try: plaintext_padded += decryptor.finalize() except ValueError: raise InvalidToken unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() unpadded = unpadder.update(plaintext_padded) try: unpadded += unpadder.finalize() except ValueError: raise InvalidToken return unpadded
Example #28
Source File: pador.py From PaddingOracleDemos with GNU General Public License v2.0 | 5 votes |
def encrypt(plain): """Adds PKCS#7 padding and encrypts with AES-128.""" iv = KEY backend = default_backend() padder = padding.PKCS7(BLOCK_SIZE).padder() padded_data = padder.update(bytes(plain)) + padder.finalize() cipher = Cipher(algorithms.AES(KEY), modes.CBC(iv), backend=backend) encryptor = cipher.encryptor() crypted = encryptor.update(padded_data) + encryptor.finalize() return crypted
Example #29
Source File: certificate.py From calvin-base with Apache License 2.0 | 5 votes |
def _unwrap_object_with_symmetric_key(wrapped_object): import json import base64 from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend backend = default_backend() #Decode base64 try: key = base64.b64decode(wrapped_object['symmetric_key']) iv = base64.b64decode(wrapped_object['iv']) ciphertext = base64.b64decode(wrapped_object['ciphertext']) except Exception as err: _log.error("Failed to decode base64 encoding of key, IV or ciphertext, err={}".format(err)) raise #Decrypt try: cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) decryptor = cipher.decryptor() padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() except Exception as err: _log.error("_unwrap_object_with_symmetric_key: Failed to decrypt, err={}".format(err)) raise #Remove padding unpadder = padding.PKCS7(128).unpadder() plaintext = unpadder.update(padded_plaintext) return plaintext + unpadder.finalize() #TODO: Add integrity protection of object, i.e., # implement proper RSA-KEM+DEM1 or RSA-REACT
Example #30
Source File: miio.py From mihome-binary-protocol with GNU General Public License v3.0 | 5 votes |
def AES_cbc_decrypt(token: bytes, ciphertext: bytes) -> bytes: """Decrypt cipher text with device token.""" key, iv = key_iv(token) cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=_backend) decryptor = cipher.decryptor() padded_plaintext = decryptor.update(bytes(ciphertext)) \ + decryptor.finalize() unpadder = padding.PKCS7(128).unpadder() unpadded_plaintext = unpadder.update(padded_plaintext) unpadded_plaintext += unpadder.finalize() return unpadded_plaintext