query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
aes encryption
python
def aes_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#bytes) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( "zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'Hello, world' ..f """ iv = os.urandom(block_size * 2) cipher = AES.new(secret[:32], AES.MODE_CFB, iv[:block_size]) return b'%s%s' % (iv, cipher.encrypt(value))
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L79-L98
aes encryption
python
def aes_decrypt(value, secret, block_size=AES.block_size): """ AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( "zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'Hello, world' .. """ if value is not None: cipher = AES.new(secret[:32], AES.MODE_CFB, value[:block_size]) return cipher.decrypt(uniorbytes(value[block_size * 2:], bytes))
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L101-L120
aes encryption
python
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( "zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'Hello, world' .. """ # iv = randstr(block_size * 2, rng=random) iv = randstr(block_size * 2) cipher = AES.new(secret[:32], AES.MODE_CFB, iv[:block_size].encode()) return iv + b64encode(cipher.encrypt( uniorbytes(value, bytes))).decode('utf-8')
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L31-L52
aes encryption
python
def aes_encrypt(mode, aes_key, aes_iv, *data): """Encrypt data with AES in specified mode.""" encryptor = Cipher( algorithms.AES(aes_key), mode(aes_iv), backend=default_backend()).encryptor() result = None for value in data: result = encryptor.update(value) encryptor.finalize() return result, None if not hasattr(encryptor, 'tag') else encryptor.tag
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L33-L45
aes encryption
python
def aes_b64_decrypt(value, secret, block_size=AES.block_size): """ AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( "zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=", "aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW") # -> 'Hello, world' .. """ if value is not None: iv = value[:block_size] cipher = AES.new(secret[:32], AES.MODE_CFB, iv) return cipher.decrypt(b64decode( uniorbytes(value[block_size * 2:], bytes))).decode('utf-8')
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L55-L76
aes encryption
python
def _aes_encrypt(data, algorithm, key): '''AES encrypt''' if algorithm['subtype'] == 'cbc': mode = AES.MODE_CBC else: raise Exception('AES subtype not supported: %s' % algorithm['subtype']) iv_size = algorithm['iv_size'] block_size = iv_size include_iv = True if 'iv'in algorithm and algorithm['iv']: if len(algorithm['iv']) != algorithm['iv_size']: raise Exception('Invalid IV size') iv_value = algorithm['iv'] include_iv = False else: iv_value = get_random_bytes(iv_size) numpad = block_size - (len(data) % block_size) data = data + numpad * chr(numpad) enc = AES.new(key, mode, iv_value).encrypt(data) if include_iv: enc = iv_value + enc return enc
https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L728-L757
aes encryption
python
def aes_encrypt(self, plain, sec_key, enable_b64=True): """ 使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type plain: str :param sec_key: :type sec_key: str :param enable_b64: :type enable_b64: bool :return: :rtype: """ plain = helper.to_str(plain) sec_key = helper.to_str(sec_key) # 如果msg长度不为16倍数, 需要补位 '\0' plain += '\0' * (self.bs - len(plain) % self.bs) # 使用生成的 key, iv 加密 plain = helper.to_bytes(plain) cipher = self.aes_obj(sec_key).encrypt(plain) # 是否返回 base64 编码数据 cip = base64.b64encode(cipher) if enable_b64 else cipher return helper.to_str(cip)
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L80-L108
aes encryption
python
def encrypt(self, key): """This method encrypts and signs the state to make it unreadable by the server, since it contains information that would allow faking proof of storage. :param key: the key to encrypt and sign with """ if (self.encrypted): return # encrypt self.iv = Random.new().read(AES.block_size) aes = AES.new(key, AES.MODE_CFB, self.iv) self.f_key = aes.encrypt(self.f_key) self.alpha_key = aes.encrypt(self.alpha_key) self.encrypted = True # sign self.hmac = self.get_hmac(key)
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L162-L178
aes encryption
python
def aes_encrypt(key: bytes, plain_text: bytes) -> bytes: """ AES-GCM encryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys plain_text: bytes Plain text to encrypt Returns ------- bytes nonce(16 bytes) + tag(16 bytes) + encrypted data """ aes_cipher = AES.new(key, AES_CIPHER_MODE) encrypted, tag = aes_cipher.encrypt_and_digest(plain_text) cipher_text = bytearray() cipher_text.extend(aes_cipher.nonce) cipher_text.extend(tag) cipher_text.extend(encrypted) return bytes(cipher_text)
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/utils.py#L159-L182
aes encryption
python
async 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()
https://github.com/terrycain/aioboto3/blob/0fd192175461f7bb192f3ed9a872591caf8474ac/aioboto3/s3/cse.py#L196-L213
aes encryption
python
def aes_ecb_encrypt(self, key_handle, plaintext): """ AES ECB encrypt using a key handle. @warning: Please be aware of the known limitations of AES ECB mode before using it! @param key_handle: Key handle to use for AES ECB encryption @param plaintext: Data to encrypt @type key_handle: integer or string @type plaintext: string @returns: Ciphertext @rtype: string @see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt} """ return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt( \ self.stick, key_handle, plaintext).execute()
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L505-L522
aes encryption
python
def aes_encrypt(base64_encryption_key, data): """Encrypt data with AES-CBC and sign it with HMAC-SHA256 Arguments: base64_encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a byte string containing the data to be encrypted Returns: str: the encrypted data as a byte string with the HMAC signature appended to the end """ if isinstance(data, text_type): data = data.encode("UTF-8") aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key) data = _pad(data) iv_bytes = os.urandom(AES_BLOCK_SIZE) cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes) data = iv_bytes + cipher.encrypt(data) # prepend init vector hmac_signature = hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() return as_base64(data + hmac_signature)
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/crypt.py#L77-L97
aes encryption
python
def cipher(rkey, pt, Nk=4): """AES encryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) pt = pt.reshape(128) # first round state = add_round_key(pt, rkey[0:4]) for i in range(1, Nr): state = sub_bytes(state) state = shift_rows(state) state = mix_columns(state) state = add_round_key(state, rkey[4*i:4*(i+1)]) # final round state = sub_bytes(state) state = shift_rows(state) state = add_round_key(state, rkey[4*Nr:4*(Nr+1)]) return state
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L323-L345
aes encryption
python
def encrypt(self, sa, esp, key): """ Encrypt an ESP packet @param sa: the SecurityAssociation associated with the ESP packet. @param esp: an unencrypted _ESPPlain packet with valid padding @param key: the secret key used for encryption @return: a valid ESP packet encrypted with this algorithm """ data = esp.data_for_encryption() if self.cipher: mode_iv = self._format_mode_iv(algo=self, sa=sa, iv=esp.iv) cipher = self.new_cipher(key, mode_iv) encryptor = cipher.encryptor() if self.is_aead: aad = struct.pack('!LL', esp.spi, esp.seq) encryptor.authenticate_additional_data(aad) data = encryptor.update(data) + encryptor.finalize() data += encryptor.tag[:self.icv_size] else: data = encryptor.update(data) + encryptor.finalize() return ESP(spi=esp.spi, seq=esp.seq, data=esp.iv + data)
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/ipsec.py#L341-L366
aes encryption
python
def auth_decrypt(self, A, C, seq_num): """ Decrypt the data and verify the authentication code (in this order). Note that TLS 1.3 is not supposed to use any additional data A. If the verification fails, an AEADTagError is raised. It is the user's responsibility to catch it if deemed useful. If we lack the key, we raise a CipherError which contains the encrypted input. """ C, mac = C[:-self.tag_len], C[-self.tag_len:] if False in six.itervalues(self.ready): raise CipherError(C, mac) if hasattr(self, "pc_cls"): self._cipher.mode._initialization_vector = self._get_nonce(seq_num) self._cipher.mode._tag = mac decryptor = self._cipher.decryptor() decryptor.authenticate_additional_data(A) P = decryptor.update(C) try: decryptor.finalize() except InvalidTag: raise AEADTagError(P, mac) else: try: if (conf.crypto_valid_advanced and isinstance(self._cipher, AESCCM)): P = self._cipher.decrypt(self._get_nonce(seq_num), C + mac, A, # noqa: E501 tag_length=self.tag_len) else: if (conf.crypto_valid_advanced and isinstance(self, Cipher_CHACHA20_POLY1305)): A += struct.pack("!H", len(C)) P = self._cipher.decrypt(self._get_nonce(seq_num), C + mac, A) # noqa: E501 except InvalidTag: raise AEADTagError("<unauthenticated data>", mac) return P, mac
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/crypto/cipher_aead.py#L335-L370
aes encryption
python
def EncryptPrivateKey(self, decrypted): """ Encrypt the provided plaintext with the initialized private key. Args: decrypted (byte string): the plaintext to be encrypted. Returns: bytes: the ciphertext. """ aes = AES.new(self._master_key, AES.MODE_CBC, self._iv) return aes.encrypt(decrypted)
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L286-L297
aes encryption
python
async 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 """ if self.public_key is None: raise ValueError('Public key not provided during initialisation, cannot encrypt key encrypting key') random_bytes = os.urandom(32) ciphertext = await self._loop.run_in_executor( None, lambda: (self.public_key.encrypt(random_bytes, padding.PKCS1v15()))) return random_bytes, {}, base64.b64encode(ciphertext).decode()
https://github.com/terrycain/aioboto3/blob/0fd192175461f7bb192f3ed9a872591caf8474ac/aioboto3/s3/cse.py#L122-L136
aes encryption
python
def _aes_decrypt(data, algorithm, key): '''AES decrypt''' if algorithm['subtype'] == 'cbc': mode = AES.MODE_CBC else: raise Exception('AES subtype not supported: %s' % algorithm['subtype']) iv_size = algorithm['iv_size'] if 'iv' in algorithm and algorithm['iv']: if len(algorithm['iv']) != algorithm['iv_size']: raise Exception('Invalid IV size') iv_value = algorithm['iv'] enc = data else: iv_value = data[:iv_size] enc = data[iv_size:] dec = AES.new(key, mode, iv_value).decrypt(enc) numpad = ord(dec[-1]) dec = dec[0:-numpad] return dec
https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L760-L785
aes encryption
python
async 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
https://github.com/terrycain/aioboto3/blob/0fd192175461f7bb192f3ed9a872591caf8474ac/aioboto3/s3/cse.py#L178-L194
aes encryption
python
def encrypt(self, data): ''' encrypt data with AES-CBC and sign it with HMAC-SHA256 ''' aes_key, hmac_key = self.keys pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE if six.PY2: data = data + pad * chr(pad) else: data = data + salt.utils.stringutils.to_bytes(pad * chr(pad)) iv_bytes = os.urandom(self.AES_BLOCK_SIZE) if HAS_M2: cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=1, padding=False) encr = cypher.update(data) encr += cypher.final() else: cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes) encr = cypher.encrypt(data) data = iv_bytes + encr sig = hmac.new(hmac_key, data, hashlib.sha256).digest() return data + sig
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/crypt.py#L1406-L1426
aes encryption
python
def aes_decrypt(self, cipher, sec_key, enable_b64=True): """ 由 ``base64解码数据``, 然后再使用 ``aes`` 解密数据 - 使用 ``sec_key`` 解密由 ``base64解码后的cipher`` 数据 - 先base64 decode, 再解密, 最后移除补位值 'ascii \\0' :param cipher: :type cipher: str :param sec_key: :type sec_key: str :param enable_b64: :type enable_b64: bool :return: :rtype: """ cipher = base64.b64decode(cipher) if enable_b64 else cipher plain_ = self.aes_obj(sec_key).decrypt(cipher) return helper.to_str(plain_).rstrip('\0')
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L110-L129
aes encryption
python
def aes_ecb_decrypt(self, key_handle, ciphertext): """ AES ECB decrypt using a key handle. @warning: Please be aware of the known limitations of AES ECB mode before using it! @param key_handle: Key handle to use for AES ECB decryption @param ciphertext: Data to decrypt @type key_handle: integer or string @type ciphertext: string @returns: Plaintext @rtype: string @see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt} """ return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt( \ self.stick, key_handle, ciphertext).execute()
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L524-L541
aes encryption
python
def encrypt(self, encryption_algorithm, encryption_key, plain_text, cipher_mode=None, padding_method=None, iv_nonce=None, hashing_algorithm=None): """ Encrypt data using symmetric or asymmetric encryption. Args: encryption_algorithm (CryptographicAlgorithm): An enumeration specifying the encryption algorithm to use for encryption. encryption_key (bytes): The bytes of the encryption key to use for encryption. plain_text (bytes): The bytes to be encrypted. cipher_mode (BlockCipherMode): An enumeration specifying the block cipher mode to use with the encryption algorithm. Required in the general case. Optional if the encryption algorithm is RC4 (aka ARC4). If optional, defaults to None. padding_method (PaddingMethod): An enumeration specifying the padding method to use on the data before encryption. Required if the cipher mode is for block ciphers (e.g., CBC, ECB). Optional otherwise, defaults to None. iv_nonce (bytes): The IV/nonce value to use to initialize the mode of the encryption algorithm. Optional, defaults to None. If required and not provided, it will be autogenerated and returned with the cipher text. hashing_algorithm (HashingAlgorithm): An enumeration specifying the hashing algorithm to use with the encryption algorithm, if needed. Required for OAEP-based asymmetric encryption. Optional, defaults to None. Returns: dict: A dictionary containing the encrypted data, with at least the following key/value fields: * cipher_text - the bytes of the encrypted data * iv_nonce - the bytes of the IV/counter/nonce used if it was needed by the encryption scheme and if it was automatically generated for the encryption Raises: InvalidField: Raised when the algorithm is unsupported or the length is incompatible with the algorithm. CryptographicFailure: Raised when the key generation process fails. Example: >>> engine = CryptographyEngine() >>> result = engine.encrypt( ... encryption_algorithm=CryptographicAlgorithm.AES, ... encryption_key=( ... b'\xF3\x96\xE7\x1C\xCF\xCD\xEC\x1F' ... b'\xFC\xE2\x8E\xA6\xF8\x74\x28\xB0' ... ), ... plain_text=( ... b'\x00\x01\x02\x03\x04\x05\x06\x07' ... b'\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' ... ), ... cipher_mode=BlockCipherMode.CBC, ... padding_method=PaddingMethod.ANSI_X923, ... ) >>> result.get('cipher_text') b'\x18[\xb9y\x1bL\xd1\x8f\x9a\xa0e\x02b\xa3=c' >>> result.iv_counter_nonce b'8qA\x05\xc4\x86\x03\xd9=\xef\xdf\xb8ke\x9a\xa2' """ if encryption_algorithm is None: raise exceptions.InvalidField("Encryption algorithm is required.") if encryption_algorithm == enums.CryptographicAlgorithm.RSA: return self._encrypt_asymmetric( encryption_algorithm, encryption_key, plain_text, padding_method, hashing_algorithm=hashing_algorithm ) else: return self._encrypt_symmetric( encryption_algorithm, encryption_key, plain_text, cipher_mode=cipher_mode, padding_method=padding_method, iv_nonce=iv_nonce )
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/services/server/crypto/engine.py#L290-L377
aes encryption
python
def encrypt(source_text, passphrase, debug_stmt=None): """ Returns *source_text* as a base64 AES encrypted string. The full encrypted text is special crafted to be compatible with openssl. It can be decrypted with: $ echo _full_encypted_ | openssl aes-256-cbc -d -a -k _passphrase_ -p salt=... key=... iv=... _source_text_ """ if debug_stmt is None: debug_stmt = "encrypt" prefix = b'Salted__' salt = os.urandom(IV_BLOCK_SIZE - len(prefix)) key, iv_ = _openssl_key_iv(passphrase, salt) cipher = Cipher( algorithms.AES(key), modes.CBC(iv_), default_backend() ).encryptor() # PKCS#7 padding if hasattr(source_text, 'encode'): source_utf8 = source_text.encode('utf-8') else: source_utf8 = str(source_text) padding = (IV_BLOCK_SIZE - len(source_utf8) % IV_BLOCK_SIZE) if six.PY2: padding = chr(padding) * padding else: padding = bytes([padding for _ in range(padding)]) plain_text = source_utf8 + padding encrypted_text = cipher.update(plain_text) + cipher.finalize() full_encrypted = b64encode(prefix + salt + encrypted_text) _log_debug(salt, key, iv_, full_encrypted, source_text, passphrase=passphrase, debug_stmt=debug_stmt) return full_encrypted
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/crypt.py#L139-L176
aes encryption
python
def encrypt_aes_cbc(cleartext, key, iv): """ This method encrypts the content. :rtype: bytes """ if isinstance(cleartext, unicode): cleartext = cleartext.encode('utf8') elif isinstance(cleartext, bytearray): cleartext = bytes(cleartext) if not isinstance(cleartext, bytes): raise TypeError("content to encrypt must by bytes.") aes = AES.new(key, AES.MODE_CBC, iv) padding = AES.block_size - (len(cleartext) % AES.block_size) cleartext += chr(padding).encode('utf-8') * padding # the encode() is for py3k compat return aes.encrypt(cleartext)
https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/util.py#L124-L140
aes encryption
python
def encrypt(self, raw): """ Encrypts raw data using AES and then base64 encodes it. :param raw: :return: """ padded = AESCipher.pad(raw) init_vec = Random.new().read(AES.block_size) cipher = AES.new(self._key, AES.MODE_CBC, init_vec) return b64encode(init_vec + cipher.encrypt(padded))
https://github.com/anomaly/vishnu/blob/5b3a6a69beedc8554cc506ddfab273760d61dc65/vishnu/cipher.py#L51-L60
aes encryption
python
def mysql_aes_encrypt(val, key): """Mysql AES encrypt value with secret key. :param val: Plain text value. :param key: The AES key. :returns: The encrypted AES value. """ assert isinstance(val, binary_type) or isinstance(val, text_type) assert isinstance(key, binary_type) or isinstance(key, text_type) k = _mysql_aes_key(_to_binary(key)) v = _mysql_aes_pad(_to_binary(val)) e = _mysql_aes_engine(k).encryptor() return e.update(v) + e.finalize()
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L66-L79
aes encryption
python
def decrypt_email(enc_email): """ The inverse of :func:`encrypt_email`. :param enc_email: The encrypted email address. """ aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.decrypt(enc_email)
https://github.com/dfm/ugly/blob/bc09834849184552619ee926d7563ed37630accb/ugly/models.py#L53-L62
aes encryption
python
def aes_decrypt(key: bytes, cipher_text: bytes) -> bytes: """ AES-GCM decryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys cipher_text: bytes Encrypted text: nonce(16 bytes) + tag(16 bytes) + encrypted data Returns ------- bytes Plain text >>> data = b'this is test data' >>> key = get_valid_secret() >>> aes_decrypt(key, aes_encrypt(key, data)) == data True >>> import os >>> key = os.urandom(32) >>> aes_decrypt(key, aes_encrypt(key, data)) == data True """ nonce = cipher_text[:16] tag = cipher_text[16:32] ciphered_data = cipher_text[32:] aes_cipher = AES.new(key, AES_CIPHER_MODE, nonce=nonce) return aes_cipher.decrypt_and_verify(ciphered_data, tag)
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/utils.py#L185-L216
aes encryption
python
def aes(encrypt, key, data): """ One-pass AES-256-CBC used in ProcessData. Zero IV (don't panic, IV-like random nonce is included in plaintext in the first block in ProcessData). Does not use padding (data has to be already padded). :param encrypt: :param key: :param data: :return: """ cipher = AES.new(key, AES.MODE_CBC, get_zero_vector(16)) if encrypt: return cipher.encrypt(data) else: return cipher.decrypt(data)
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L350-L366
aes encryption
python
def decrypt_aes(self, payload, master_pub=True): ''' This function is used to decrypt the AES seed phrase returned from the master server. The seed phrase is decrypted with the SSH RSA host key. Pass in the encrypted AES key. Returns the decrypted AES seed key, a string :param dict payload: The incoming payload. This is a dictionary which may have the following keys: 'aes': The shared AES key 'enc': The format of the message. ('clear', 'pub', etc) 'sig': The message signature 'publish_port': The TCP port which published the message 'token': The encrypted token used to verify the message. 'pub_key': The public key of the sender. :rtype: str :return: The decrypted token that was provided, with padding. :rtype: str :return: The decrypted AES seed key ''' if self.opts.get('auth_trb', False): log.warning('Auth Called: %s', ''.join(traceback.format_stack())) else: log.debug('Decrypting the current master AES key') key = self.get_keys() if HAS_M2: key_str = key.private_decrypt(payload['aes'], RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(key) key_str = cipher.decrypt(payload['aes']) if 'sig' in payload: m_path = os.path.join(self.opts['pki_dir'], self.mpub) if os.path.exists(m_path): try: mkey = get_rsa_pub_key(m_path) except Exception: return '', '' digest = hashlib.sha256(key_str).hexdigest() if six.PY3: digest = salt.utils.stringutils.to_bytes(digest) if HAS_M2: m_digest = public_decrypt(mkey, payload['sig']) else: m_digest = public_decrypt(mkey.publickey(), payload['sig']) if m_digest != digest: return '', '' else: return '', '' if six.PY3: key_str = salt.utils.stringutils.to_str(key_str) if '_|-' in key_str: return key_str.split('_|-') else: if 'token' in payload: if HAS_M2: token = key.private_decrypt(payload['token'], RSA.pkcs1_oaep_padding) else: token = cipher.decrypt(payload['token']) return key_str, token elif not master_pub: return key_str, '' return '', ''
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/crypt.py#L847-L915
aes encryption
python
def auth_encrypt(self, P, A, seq_num=None): """ Encrypt the data then prepend the explicit part of the nonce. The authentication tag is directly appended with the most recent crypto API. Additional data may be authenticated without encryption (as A). The 'seq_num' should never be used here, it is only a safeguard needed because one cipher (ChaCha20Poly1305) using TLS 1.2 logic in record.py actually is a _AEADCipher_TLS13 (even though others are not). """ if False in six.itervalues(self.ready): raise CipherError(P, A) if hasattr(self, "pc_cls"): self._cipher.mode._initialization_vector = self._get_nonce() self._cipher.mode._tag = None encryptor = self._cipher.encryptor() encryptor.authenticate_additional_data(A) res = encryptor.update(P) + encryptor.finalize() res += encryptor.tag else: res = self._cipher.encrypt(self._get_nonce(), P, A) nonce_explicit = pkcs_i2osp(self.nonce_explicit, self.nonce_explicit_len) self._update_nonce_explicit() return nonce_explicit + res
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/crypto/cipher_aead.py#L137-L163
aes encryption
python
def aes_pad(s, block_size=32, padding='{'): """ Adds padding to get the correct block sizes for AES encryption @s: #str being AES encrypted or decrypted @block_size: the AES block size @padding: character to pad with -> padded #str .. from vital.security import aes_pad aes_pad("swing") # -> 'swing{{{{{{{{{{{{{{{{{{{{{{{{{{{' .. """ return s + (block_size - len(s) % block_size) * padding
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L123-L138
aes encryption
python
def aes_encrypt(key, stdin, preamble=None, chunk_size=65536, content_length=None): """ Generator that encrypts a content stream using AES 256 in CBC mode. :param key: Any string to use as the encryption key. :param stdin: Where to read the contents from. :param preamble: str to yield initially useful for providing a hint for future readers as to the algorithm in use. :param chunk_size: Largest amount to read at once. :param content_length: The number of bytes to read from stdin. None or < 0 indicates reading until EOF. """ if not AES256CBC_Support: raise Exception( 'AES256CBC not supported; likely pycrypto is not installed') if preamble: yield preamble # Always use 256-bit key key = hashlib.sha256(key).digest() # At least 16 and a multiple of 16 chunk_size = max(16, chunk_size >> 4 << 4) iv = Crypto.Random.new().read(16) yield iv encryptor = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv) reading = True left = None if content_length is not None and content_length >= 0: left = content_length while reading: size = chunk_size if left is not None and size > left: size = left chunk = stdin.read(size) if not chunk: if left is not None and left > 0: raise IOError('Early EOF from input') # Indicates how many usable bytes in last block yield encryptor.encrypt('\x00' * 16) break if left is not None: left -= len(chunk) if left <= 0: reading = False block = chunk trailing = len(block) % 16 while trailing: size = 16 - trailing if left is not None and size > left: size = left chunk = stdin.read(size) if not chunk: if left is not None and left > 0: raise IOError('Early EOF from input') reading = False # Indicates how many usable bytes in last block chunk = chr(trailing) * (16 - trailing) elif left is not None: left -= len(chunk) if left <= 0: reading = False block += chunk trailing = len(block) % 16 yield encryptor.encrypt(block)
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/dencrypt.py#L35-L99
aes encryption
python
async 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 """ if self.private_key is None: raise ValueError('Private key not provided during initialisation, cannot decrypt key encrypting key') plaintext = await self._loop.run_in_executor(None, lambda: (self.private_key.decrypt(key, padding.PKCS1v15()))) return plaintext
https://github.com/terrycain/aioboto3/blob/0fd192175461f7bb192f3ed9a872591caf8474ac/aioboto3/s3/cse.py#L107-L120
aes encryption
python
def DecryptPrivateKey(self, encrypted_private_key): """ Decrypt the provided ciphertext with the initialized private key. Args: encrypted_private_key (byte string): the ciphertext to be decrypted. Returns: bytes: the ciphertext. """ aes = AES.new(self._master_key, AES.MODE_CBC, self._iv) return aes.decrypt(encrypted_private_key)
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L299-L310
aes encryption
python
def _rsaes_oaep_decrypt(self, C, h=None, mgf=None, L=None): """ Internal method providing RSAES-OAEP-DECRYPT as defined in Sect. 7.1.2 of RFC 3447. Not intended to be used directly. Please, see encrypt() method for type "OAEP". Input: C : ciphertext to be decrypted, an octet string of length k, where k = 2*hLen + 2 (k denotes the length in octets of the RSA modulus and hLen the length in octets of the hash function output) h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls', 'sha256', 'sha384'). 'sha1' is used if none is provided. mgf: the mask generation function f : seed, maskLen -> mask L : optional label whose association with the message is to be verified; the default value for L, if not provided is the empty string. Output: message, an octet string of length k mLen, where mLen <= k - 2*hLen - 2 On error, None is returned. """ # The steps below are the one described in Sect. 7.1.2 of RFC 3447. # 1) Length Checking # 1.a) is not done if h is None: h = "sha1" if not h in _hashFuncParams: warning("Key._rsaes_oaep_decrypt(): unknown hash function %s.", h) return None hLen = _hashFuncParams[h][0] hFun = _hashFuncParams[h][1] k = self.modulusLen / 8 cLen = len(C) if cLen != k: # 1.b) warning("Key._rsaes_oaep_decrypt(): decryption error. " "(cLen != k)") return None if k < 2*hLen + 2: warning("Key._rsaes_oaep_decrypt(): decryption error. " "(k < 2*hLen + 2)") return None # 2) RSA decryption c = pkcs_os2ip(C) # 2.a) m = self._rsadp(c) # 2.b) EM = pkcs_i2osp(m, k) # 2.c) # 3) EME-OAEP decoding if L is None: # 3.a) L = "" lHash = hFun(L) Y = EM[:1] # 3.b) if Y != '\x00': warning("Key._rsaes_oaep_decrypt(): decryption error. " "(Y is not zero)") return None maskedSeed = EM[1:1+hLen] maskedDB = EM[1+hLen:] if mgf is None: mgf = lambda x,y: pkcs_mgf1(x, y, h) seedMask = mgf(maskedDB, hLen) # 3.c) seed = strxor(maskedSeed, seedMask) # 3.d) dbMask = mgf(seed, k - hLen - 1) # 3.e) DB = strxor(maskedDB, dbMask) # 3.f) # I am aware of the note at the end of 7.1.2 regarding error # conditions reporting but the one provided below are for _local_ # debugging purposes. --arno lHashPrime = DB[:hLen] # 3.g) tmp = DB[hLen:].split('\x01', 1) if len(tmp) != 2: warning("Key._rsaes_oaep_decrypt(): decryption error. " "(0x01 separator not found)") return None PS, M = tmp if PS != '\x00'*len(PS): warning("Key._rsaes_oaep_decrypt(): decryption error. " "(invalid padding string)") return None if lHash != lHashPrime: warning("Key._rsaes_oaep_decrypt(): decryption error. " "(invalid hash)") return None return M
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L664-L751
aes encryption
python
def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST): """ Encrypts `secret` using the key service. You can decrypt with the companion method `open_aes_ctr_legacy`. """ # generate a a 64 byte key. # Half will be for data encryption, the other half for HMAC key, encoded_key = key_service.generate_key_data(64) ciphertext, hmac = _seal_aes_ctr( secret, key, LEGACY_NONCE, digest_method, ) return { 'key': b64encode(encoded_key).decode('utf-8'), 'contents': b64encode(ciphertext).decode('utf-8'), 'hmac': codecs.encode(hmac, "hex_codec"), 'digest': digest_method, }
https://github.com/fugue/credstash/blob/56df8e051fc4c8d15d5e7e373e88bf5bc13f3346/credstash.py#L625-L641
aes encryption
python
def encrypt(data, digest=True): """Perform encryption of provided data.""" alg = get_best_algorithm() enc = implementations["encryption"][alg]( data, implementations["get_key"]() ) return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc))
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/crypto.py#L428-L434
aes encryption
python
def encrypt(self, msg, alg='aes_128_cbc', padding='PKCS#7', b64enc=True, block_size=AES_BLOCK_SIZE): """ :param key: The encryption key :param msg: Message to be encrypted :param padding: Which padding that should be used :param b64enc: Whether the result should be base64encoded :param block_size: If PKCS#7 padding which block size to use :return: The encrypted message """ self.__class__._deprecation_notice() if padding == 'PKCS#7': _block_size = block_size elif padding == 'PKCS#5': _block_size = 8 else: _block_size = 0 if _block_size: plen = _block_size - (len(msg) % _block_size) c = chr(plen).encode() msg += c * plen cipher, iv = self.build_cipher(alg) encryptor = cipher.encryptor() cmsg = iv + encryptor.update(msg) + encryptor.finalize() if b64enc: enc_msg = _base64.b64encode(cmsg) else: enc_msg = cmsg return enc_msg
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cryptography/symmetric.py#L116-L148
aes encryption
python
async 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-v2 :param material_description: JSON decoded x-amz-matdesc :return: Raw AES key bytes """ raise NotImplementedError()
https://github.com/terrycain/aioboto3/blob/0fd192175461f7bb192f3ed9a872591caf8474ac/aioboto3/s3/cse.py#L67-L75
aes encryption
python
def init_aes(shared_secret, nonce): """ Initialize AES instance :param hex shared_secret: Shared Secret to use as encryption key :param int nonce: Random nonce :return: AES instance :rtype: AES """ " Shared Secret " ss = hashlib.sha512(unhexlify(shared_secret)).digest() " Seed " seed = bytes(str(nonce), "ascii") + hexlify(ss) seed_digest = hexlify(hashlib.sha512(seed).digest()).decode("ascii") " AES " key = unhexlify(seed_digest[0:64]) iv = unhexlify(seed_digest[64:96]) return AES.new(key, AES.MODE_CBC, iv)
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/memo.py#L40-L57
aes encryption
python
def create_rsa_encrypted_pem(private_key, passphrase): """ <Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the algorithm may change over time. c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/ #cryptography.hazmat.primitives.serialization.BestAvailableEncryption >>> rsa_key = generate_rsa_key() >>> private = rsa_key['keyval']['private'] >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_key: The private key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the RSA key. 'passphrase' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if an RSA key in encrypted PEM format cannot be created. TypeError, 'private_key' is unset. <Side Effects> None. <Returns> A string in PEM format, where the private RSA key is encrypted. Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'. """ # Does 'private_key' have the correct format? # This check will ensure 'private_key' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key) # Does 'passphrase' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) encrypted_pem = None # Generate the public and private RSA keys. A 2048-bit minimum is enforced by # create_rsa_encrypted_pem() via a # securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(). encrypted_pem = securesystemslib.pyca_crypto_keys.create_rsa_encrypted_pem( private_key, passphrase) return encrypted_pem
https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/keys.py#L1413-L1474
aes encryption
python
def create_rsa_encrypted_pem(private_key, passphrase): """ <Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the algorithm may change over time. c.f. cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/ #cryptography.hazmat.primitives.serialization.BestAvailableEncryption >>> public, private = generate_rsa_public_and_private(2048) >>> passphrase = 'secret' >>> encrypted_pem = create_rsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_key: The private key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the RSA key. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if the passed RSA key cannot be deserialized by pyca cryptography. ValueError, if 'private_key' is unset. <Returns> A string in PEM format (TraditionalOpenSSL), where the private RSA key is encrypted. Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'. """ # This check will ensure 'private_key' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key) # Does 'passphrase' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) # 'private_key' may still be a NULL string after the # 'securesystemslib.formats.PEMRSA_SCHEMA' so we need an additional check if len(private_key): try: private_key = load_pem_private_key(private_key.encode('utf-8'), password=None, backend=default_backend()) except ValueError: raise securesystemslib.exceptions.CryptoError('The private key' ' (in PEM format) could not be deserialized.') else: raise ValueError('The required private key is unset.') encrypted_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption( passphrase.encode('utf-8'))) return encrypted_pem.decode()
https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/pyca_crypto_keys.py#L455-L522
aes encryption
python
def encrypt(self, data, unique_identifier=None, cryptographic_parameters=None, iv_counter_nonce=None, credential=None): """ Encrypt data using the specified encryption key and parameters. Args: data (bytes): The bytes to encrypt. Required. unique_identifier (string): The unique ID of the encryption key to use. Optional, defaults to None. cryptographic_parameters (CryptographicParameters): A structure containing various cryptographic settings to be used for the encryption. Optional, defaults to None. iv_counter_nonce (bytes): The bytes to use for the IV/counter/ nonce, if needed by the encryption algorithm and/or cipher mode. Optional, defaults to None. credential (Credential): A credential object containing a set of authorization parameters for the operation. Optional, defaults to None. Returns: dict: The results of the encrypt operation, containing the following key/value pairs: Key | Value --------------------|----------------------------------------- 'unique_identifier' | (string) The unique ID of the encryption | key used to encrypt the data. 'data' | (bytes) The encrypted data. 'iv_counter_nonce' | (bytes) The IV/counter/nonce used for | the encryption, if autogenerated. 'result_status' | (ResultStatus) An enumeration indicating | the status of the operation result. 'result_reason' | (ResultReason) An enumeration providing | context for the result status. 'result_message' | (string) A message providing additional | context for the operation result. """ operation = Operation(OperationEnum.ENCRYPT) request_payload = payloads.EncryptRequestPayload( unique_identifier=unique_identifier, data=data, cryptographic_parameters=cryptographic_parameters, iv_counter_nonce=iv_counter_nonce ) batch_item = messages.RequestBatchItem( operation=operation, request_payload=request_payload ) request = self._build_request_message(credential, [batch_item]) response = self._send_and_receive_message(request) batch_item = response.batch_items[0] payload = batch_item.response_payload result = {} if payload: result['unique_identifier'] = payload.unique_identifier result['data'] = payload.data result['iv_counter_nonce'] = payload.iv_counter_nonce result['result_status'] = batch_item.result_status.value try: result['result_reason'] = batch_item.result_reason.value except Exception: result['result_reason'] = batch_item.result_reason try: result['result_message'] = batch_item.result_message.value except Exception: result['result_message'] = batch_item.result_message return result
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/services/kmip_client.py#L741-L817
aes encryption
python
def encrypt_email(email): """ The default encryption function for storing emails in the database. This uses AES and the encryption key defined in the applications configuration. :param email: The email address. """ aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.encrypt(email)
https://github.com/dfm/ugly/blob/bc09834849184552619ee926d7563ed37630accb/ugly/models.py#L40-L50
aes encryption
python
def create_ecdsa_encrypted_pem(private_pem, passphrase): """ <Purpose> Return a string in PEM format, where the private part of the ECDSA key is encrypted. The private part of the ECDSA key is encrypted as done by pyca/cryptography: "Encrypt using the best available encryption for a given key's backend. This is a curated encryption choice and the algorithm may change over time." >>> junk, private = generate_public_and_private() >>> passphrase = 'secret' >>> encrypted_pem = create_ecdsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_pem: The private ECDSA key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the ECDSA key. 'passphrase' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if an ECDSA key in encrypted PEM format cannot be created. <Side Effects> None. <Returns> A string in PEM format, where the private RSA portion is encrypted. Conforms to 'securesystemslib.formats.PEMECDSA_SCHEMA'. """ # Does 'private_key' have the correct format? # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_pem) # Does 'passphrase' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) encrypted_pem = None private = load_pem_private_key(private_pem.encode('utf-8'), password=None, backend=default_backend()) encrypted_private_pem = \ private.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption(passphrase.encode('utf-8'))) return encrypted_private_pem
https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/ecdsa_keys.py#L411-L467
aes encryption
python
def encrypt(self, k, a, m): """ Encrypt according 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. """ hkey = k[:_inbytes(self.keysize)] ekey = k[_inbytes(self.keysize):] # encrypt iv = _randombits(self.blocksize) cipher = Cipher(algorithms.AES(ekey), modes.CBC(iv), backend=self.backend) encryptor = cipher.encryptor() padder = PKCS7(self.blocksize).padder() padded_data = padder.update(m) + padder.finalize() e = encryptor.update(padded_data) + encryptor.finalize() # mac t = self._mac(hkey, a, iv, e) return (iv, e, t)
https://github.com/latchset/jwcrypto/blob/961df898dc08f63fe3d900f2002618740bc66b4a/jwcrypto/jwa.py#L861-L886
aes encryption
python
def decrypt(source_text, passphrase, debug_stmt=None): """ Returns plain text from *source_text*, a base64 AES encrypted string as generated with openssl. $ echo '_source_text_' | openssl aes-256-cbc -a -k _passphrase_ -p salt=... key=... iv=... _full_encrypted_ """ if debug_stmt is None: debug_stmt = "decrypt" full_encrypted = b64decode(source_text) salt = full_encrypted[8:IV_BLOCK_SIZE] encrypted_text = full_encrypted[IV_BLOCK_SIZE:] key, iv_ = _openssl_key_iv(passphrase, salt) cipher = Cipher( algorithms.AES(key), modes.CBC(iv_), default_backend() ).decryptor() plain_text = cipher.update(encrypted_text) plain_text += cipher.finalize() # PKCS#7 padding if six.PY2: padding = ord(plain_text[-1]) else: padding = plain_text[-1] plain_text = plain_text[:-padding] if hasattr(plain_text, 'decode'): plain_text = plain_text.decode('utf-8') _log_debug(salt, key, iv_, source_text, plain_text, passphrase=passphrase, debug_stmt=debug_stmt) return plain_text
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/crypt.py#L104-L136
aes encryption
python
def rsa_decrypt(encrypted_data, pem, password=None): """ rsa 解密 :param encrypted_data: 待解密 bytes :param pem: RSA private key 内容/binary :param password: RSA private key pass phrase :return: 解密后的 binary """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding encrypted_data = to_binary(encrypted_data) pem = to_binary(pem) private_key = serialization.load_pem_private_key(pem, password, backend=default_backend()) data = private_key.decrypt( encrypted_data, padding=padding.OAEP( mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None, ) ) return data
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/pay/utils.py#L97-L121
aes encryption
python
def encrypt(self, raw): """ Encryptes the parameter raw. :type raw: bytes :rtype: str :param: bytes to be encrypted. :return: A base 64 encoded string. """ raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.urlsafe_b64encode(iv + cipher.encrypt(raw))
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L109-L123
aes encryption
python
def old_encode_aes(key, plaintext): """ Utility method to encode some given plaintext with the given key. Important thing to note: This is not a general purpose encryption method - it has specific semantics (see below for details). Takes the given key, pads it to 32 bytes. Then takes the given plaintext and pads that to a 32 byte block size. Then encrypts using AES-256-CBC using a random IV. Then converts both the IV and the ciphertext to hex. Finally returns the IV appended by the ciphertext. :param key: string, <= 32 bytes long :param plaintext: string, any amount of data """ # generate 16 cryptographically secure random bytes for our IV (initial value) iv = os.urandom(16) # set up an AES cipher object cipher = AES.new(ensure_bytes(old_pad(key)), mode=AES.MODE_CBC, IV=iv) # encrypte the plaintext after padding it ciphertext = cipher.encrypt(ensure_bytes(old_pad(plaintext))) # append the hexed IV and the hexed ciphertext iv_plus_encrypted = binascii.hexlify(iv) + binascii.hexlify(ciphertext) # return that return iv_plus_encrypted
https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/scoped_keys.py#L134-L157
aes encryption
python
def aes_decrypt(base64_encryption_key, base64_data): """Verify HMAC-SHA256 signature and decrypt data with AES-CBC Arguments: encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a byte string containing the data decrypted with an HMAC signing key appended to the end Returns: str: a byte string containing the data that was originally encrypted Raises: AuthenticationError: when the HMAC-SHA256 signature authentication fails """ data = from_base64(base64_data) aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key) data, hmac_signature = data[:-HMAC_SIG_SIZE], data[-HMAC_SIG_SIZE:] if hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() != hmac_signature: raise AuthenticationError("HMAC authentication failed") iv_bytes, data = data[:AES_BLOCK_SIZE], data[AES_BLOCK_SIZE:] cipher = AES.new(aes_key_bytes, AES.MODE_CBC, iv_bytes) data = cipher.decrypt(data) return _unpad(data)
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/crypt.py#L100-L124
aes encryption
python
def _encrypt(data): """Equivalent to OpenSSL using 256 bit AES in CBC mode""" BS = AES.block_size def pad(s): n = BS - len(s) % BS char = chr(n).encode('utf8') return s + n * char password = settings.GECKOBOARD_PASSWORD salt = Random.new().read(BS - len('Salted__')) key, iv = _derive_key_and_iv(password, salt, 32, BS) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted = b'Salted__' + salt + cipher.encrypt(pad(data)) return base64.b64encode(encrypted)
https://github.com/jcassee/django-geckoboard/blob/6ebdaa86015fe645360abf1ba1290132de4cf6d6/django_geckoboard/decorators.py#L446-L460
aes encryption
python
def decode_aes256(cipher, iv, data, encryption_key): """ Decrypt AES-256 bytes. Allowed ciphers are: :ecb, :cbc. If for :ecb iv is not used and should be set to "". """ if cipher == 'cbc': aes = AES.new(encryption_key, AES.MODE_CBC, iv) elif cipher == 'ecb': aes = AES.new(encryption_key, AES.MODE_ECB) else: raise ValueError('Unknown AES mode') d = aes.decrypt(data) # http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/ unpad = lambda s: s[0:-ord(d[-1:])] return unpad(d)
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L269-L284
aes encryption
python
def aesCCM(key, key_handle, nonce, data, decrypt=False): """ Function implementing YubiHSM AEAD encrypt/decrypt in software. """ if decrypt: (data, saved_mac) = _split_data(data, len(data) - pyhsm.defines.YSM_AEAD_MAC_SIZE) nonce = pyhsm.util.input_validate_nonce(nonce, pad = True) mac = _cbc_mac(key, key_handle, nonce, len(data)) counter = _ctr_counter(key_handle, nonce, value = 0) ctr_aes = AES.new(key, AES.MODE_CTR, counter = counter.next) out = [] while data: (thisblock, data) = _split_data(data, pyhsm.defines.YSM_BLOCK_SIZE) # encrypt/decrypt and CBC MAC if decrypt: aes_out = ctr_aes.decrypt(thisblock) mac.update(aes_out) else: mac.update(thisblock) aes_out = ctr_aes.encrypt(thisblock) out.append(aes_out) # Finalize MAC counter.value = 0 mac.finalize(counter.pack()) if decrypt: if mac.get() != saved_mac: raise pyhsm.exception.YHSM_Error('AEAD integrity check failed') else: out.append(mac.get()) return ''.join(out)
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L95-L129
aes encryption
python
def decrypt(self, encrypted): """ Base64 decodes the data and then decrypts using AES. :param encrypted: :return: """ decoded = b64decode(encrypted) init_vec = decoded[:AES.block_size] cipher = AES.new(self._key, AES.MODE_CBC, init_vec) return AESCipher.unpad(cipher.decrypt(decoded[AES.block_size:]))
https://github.com/anomaly/vishnu/blob/5b3a6a69beedc8554cc506ddfab273760d61dc65/vishnu/cipher.py#L62-L72
aes encryption
python
def encrypt(self, data, *args, **kwargs): ''' Sign/Encrypt :param data: Data to encrypt :param recipients: Single key ID or list of mutiple IDs. Will be ignored if symmetric :param sign_key: Key for signing data before encryption. No sign will be made when not given :param passphrase: Password for key or symmetric cipher :param always_trust: Skip key validation and assume that used keys are always fully trusted :param output_filename: Encrypted data will be written to this file when not None :param binary: If false, create ASCII armored output :param symmetric: Encrypt with symmetric cipher only :rtype: EncryptResult ''' return self.encrypt_file(self.create_stream(data), *args, **kwargs)
https://github.com/UncleRus/regnupg/blob/c1acb5d459107c70e45967ec554831a5f2cd1aaf/regnupg.py#L989-L1003
aes encryption
python
def encrypt(self, key_password): """ Encrypts the private key, so that it can be saved to a keystore. This will make it necessary to decrypt it again if it is going to be used later. Has no effect if the entry is already encrypted. :param str key_password: The password to encrypt the entry with. """ if not self.is_decrypted(): return encrypted_private_key = sun_crypto.jks_pkey_encrypt(self.pkey_pkcs8, key_password) a = AlgorithmIdentifier() a.setComponentByName('algorithm', sun_crypto.SUN_JKS_ALGO_ID) a.setComponentByName('parameters', '\x05\x00') epki = rfc5208.EncryptedPrivateKeyInfo() epki.setComponentByName('encryptionAlgorithm',a) epki.setComponentByName('encryptedData', encrypted_private_key) self._encrypted = encoder.encode(epki) self._pkey = None self._pkey_pkcs8 = None self._algorithm_oid = None
https://github.com/kurtbrose/pyjks/blob/1cbe7f060e2ad076b6462f3273f11d635771ea3d/jks/jks.py#L229-L253
aes encryption
python
def to_aes_key(password): """Compute/Derivate a key to be used in AES encryption from the password To maintain compatibility with the reference implementation the resulting key should be a sha256 hash of the sha256 hash of the password """ password_hash = hashlib.sha256(password.encode('utf-8')).digest() return hashlib.sha256(password_hash).digest()
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/utils.py#L4-L11
aes encryption
python
def encrypt(s, base64 = False): """ 对称加密函数 """ e = _cipher().encrypt(s) return base64 and b64encode(e) or e
https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/utility.py#L83-L88
aes encryption
python
def encrypt(self, msg): """encrypts a message""" iv = self.random_bytes(AES.block_size) ctr = Counter.new(AES.block_size * 8, initial_value=self.bin2long(iv)) cipher = AES.AESCipher(self._cipherkey, AES.MODE_CTR, counter=ctr) cipher_text = cipher.encrypt(msg) intermediate = iv + cipher_text signature = self.sign(intermediate) return signature + intermediate
https://github.com/gilsho/kryptonite/blob/d20a15e4fd28cb880180b827099168dd87eb0291/kryptonite/cipher.py#L54-L62
aes encryption
python
def _encrypt(self, dec, password=None): """ Internal encryption function Uses either the password argument for the encryption, or, if not supplied, the password field of the object :param dec: a byte string representing the to be encrypted data :rtype: bytes """ if AES is None: raise ImportError("PyCrypto required") if password is None: password = self.password if password is None: raise ValueError( "Password need to be provided to create encrypted archives") # generate the different encryption parts (non-secure!) master_key = Random.get_random_bytes(32) master_salt = Random.get_random_bytes(64) user_salt = Random.get_random_bytes(64) master_iv = Random.get_random_bytes(16) user_iv = Random.get_random_bytes(16) rounds = 10000 # create the PKCS#7 padding l = len(dec) pad = 16 - (l % 16) dec += bytes([pad] * pad) # encrypt the data cipher = AES.new(master_key, IV=master_iv, mode=AES.MODE_CBC) enc = cipher.encrypt(dec) # generate the master key checksum master_ck = PBKDF2(self.encode_utf8(master_key), master_salt, dkLen=256//8, count=rounds) # generate the user key from the given password user_key = PBKDF2(password, user_salt, dkLen=256//8, count=rounds) # encrypt the master key and iv master_dec = b"\x10" + master_iv + b"\x20" + master_key + b"\x20" + master_ck l = len(master_dec) pad = 16 - (l % 16) master_dec += bytes([pad] * pad) cipher = AES.new(user_key, IV=user_iv, mode=AES.MODE_CBC) master_enc = cipher.encrypt(master_dec) # put everything together enc = binascii.b2a_hex(user_salt).upper() + b"\n" + \ binascii.b2a_hex(master_salt).upper() + b"\n" + \ str(rounds).encode() + b"\n" + \ binascii.b2a_hex(user_iv).upper() + b"\n" + \ binascii.b2a_hex(master_enc).upper() + b"\n" + enc return enc
https://github.com/bluec0re/android-backup-tools/blob/e2e0d95e56624c1a99a176df9e307398e837d908/android_backup/android_backup.py#L258-L318
aes encryption
python
def mysql_aes_decrypt(encrypted_val, key): """Mysql AES decrypt value with secret key. :param encrypted_val: Encrypted value. :param key: The AES key. :returns: The AES value decrypted. """ assert isinstance(encrypted_val, binary_type) \ or isinstance(encrypted_val, text_type) assert isinstance(key, binary_type) or isinstance(key, text_type) k = _mysql_aes_key(_to_binary(key)) d = _mysql_aes_engine(_to_binary(k)).decryptor() return _mysql_aes_unpad(d.update(_to_binary(encrypted_val)) + d.finalize())
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L82-L94
aes encryption
python
def auth_encrypt(self, P, A, seq_num): """ Encrypt the data, and append the computed authentication code. TLS 1.3 does not use additional data, but we leave this option to the user nonetheless. Note that the cipher's authentication tag must be None when encrypting. """ if False in six.itervalues(self.ready): raise CipherError(P, A) if hasattr(self, "pc_cls"): self._cipher.mode._tag = None self._cipher.mode._initialization_vector = self._get_nonce(seq_num) encryptor = self._cipher.encryptor() encryptor.authenticate_additional_data(A) res = encryptor.update(P) + encryptor.finalize() res += encryptor.tag else: if (conf.crypto_valid_advanced and isinstance(self._cipher, AESCCM)): res = self._cipher.encrypt(self._get_nonce(seq_num), P, A, tag_length=self.tag_len) else: res = self._cipher.encrypt(self._get_nonce(seq_num), P, A) return res
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/crypto/cipher_aead.py#L308-L333
aes encryption
python
def decrypt(self, esp, key, icv_size=None): """ Decrypt an ESP packet @param esp: an encrypted ESP packet @param key: the secret key used for encryption @param icv_size: the length of the icv used for integrity check @return: a valid ESP packet encrypted with this algorithm @raise IPSecIntegrityError: if the integrity check fails with an AEAD algorithm """ if icv_size is None: icv_size = self.icv_size if self.is_aead else 0 iv = esp.data[:self.iv_size] data = esp.data[self.iv_size:len(esp.data) - icv_size] icv = esp.data[len(esp.data) - icv_size:] if self.cipher: cipher = self.new_cipher(key, iv, icv) decryptor = cipher.decryptor() if self.is_aead: # Tag value check is done during the finalize method decryptor.authenticate_additional_data( struct.pack('!LL', esp.spi, esp.seq) ) try: data = decryptor.update(data) + decryptor.finalize() except InvalidTag as err: raise IPSecIntegrityError(err) # extract padlen and nh padlen = (data[-2]) nh = data[-1] # then use padlen to determine data and padding data = data[:len(data) - padlen - 2] padding = data[len(data) - padlen - 2: len(data) - 2] return _ESPPlain(spi=esp.spi, seq=esp.seq, iv=iv, data=data, padding=padding, padlen=padlen, nh=nh, icv=icv)
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/layers/ipsec.py#L338-L387
aes encryption
python
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)
https://github.com/latchset/jwcrypto/blob/961df898dc08f63fe3d900f2002618740bc66b4a/jwcrypto/jwa.py#L960-L977
aes encryption
python
def aes_cbc_pkcs7_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by OpenSSL :return: A byte string of the plaintext """ cipher = _calculate_aes_cipher(key) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt(cipher, key, data, iv, True)
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/symmetric.py#L152-L184
aes encryption
python
def aes_cbc_no_padding_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by OpenSSL :return: A byte string of the plaintext """ cipher = _calculate_aes_cipher(key) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt(cipher, key, data, iv, False)
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/symmetric.py#L77-L110
aes encryption
python
def encrypt(self, msg, iv='', auth_data=None): """ Encrypts and authenticates the data provided as well as authenticating the associated_data. :param msg: The message to be encrypted :param iv: MUST be present, at least 96-bit long :param auth_data: Associated data :return: The cipher text bytes with the 16 byte tag appended. """ if not iv: raise ValueError('Missing Nonce') return self.key.encrypt(iv, msg, auth_data)
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/aes.py#L106-L119
aes encryption
python
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L315-L337
aes encryption
python
def decrypt(self, text, appid): """对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文 """ try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception as e: raise DecryptAESError(e) try: if six.PY2: pad = ord(plain_text[-1]) else: pad = plain_text[-1] # 去掉补位字符串 # pkcs7 = PKCS7Encoder() # plain_text = pkcs7.encode(plain_text) # 去除16位随机字符串 content = plain_text[16:-pad] xml_len = socket.ntohl(struct.unpack("I", content[: 4])[0]) xml_content = content[4: xml_len + 4] from_appid = content[xml_len + 4:] except Exception as e: raise IllegalBuffer(e) if from_appid != appid: raise ValidateAppIDError() return xml_content
https://github.com/doraemonext/wechat-python-sdk/blob/bf6f6f3d4a5440feb73a51937059d7feddc335a0/wechat_sdk/lib/crypto/base.py#L45-L75
aes encryption
python
def encrypt(self, data): """ :type data: any :rtype: any """ data = force_bytes(data) iv = os.urandom(16) return self._encrypt_from_parts(data, iv)
https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/utils/crypto.py#L113-L120
aes encryption
python
def encrypt(self, m, t=None, h=None, mgf=None, L=None): """ Encrypt message 'm' using 't' encryption scheme where 't' can be: - None: the message 'm' is directly applied the RSAEP encryption primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.1.1. Simply put, the message undergo a modular exponentiation using the public key. Additionnal method parameters are just ignored. - 'pkcs': the message 'm' is applied RSAES-PKCS1-V1_5-ENCRYPT encryption scheme as described in section 7.2.1 of RFC 3447. In that context, other parameters ('h', 'mgf', 'l') are not used. - 'oaep': the message 'm' is applied the RSAES-OAEP-ENCRYPT encryption scheme, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 7.1.1. In that context, o 'h' parameter provides the name of the hash method to use. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". if none is provided, sha1 is used. o 'mgf' is the mask generation function. By default, mgf is derived from the provided hash function using the generic MGF1 (see pkcs_mgf1() for details). o 'L' is the optional label to be associated with the message. If not provided, the default value is used, i.e the empty string. No check is done on the input limitation of the hash function regarding the size of 'L' (for instance, 2^61 - 1 for SHA-1). You have been warned. """ if h is not None: h = mapHashFunc(h) if t is None: # Raw encryption return self.key.encrypt( m, padding.AssymmetricPadding(), ) elif t == "pkcs": return self.key.encrypt( m, padding.PKCS1v15(), ) elif t == "oaep": return self.key.encrypt( m, padding.OAEP( mgf=mgf(h()), algorithm=h(), label=L, ), ) else: warning("Key.encrypt(): Unknown encryption type (%s) provided" % t) return None
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L446-L505
aes encryption
python
def encrypt(self, plaintext_data_key, encryption_context): """Encrypts a data key using a direct wrapping key. :param bytes plaintext_data_key: Data key to encrypt :param dict encryption_context: Encryption context to use in encryption :returns: Deserialized object containing encrypted key :rtype: aws_encryption_sdk.internal.structures.EncryptedData """ if self.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC: if self.wrapping_key_type is EncryptionKeyType.PRIVATE: encrypted_key = self._wrapping_key.public_key().encrypt( plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding ) else: encrypted_key = self._wrapping_key.encrypt( plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding ) return EncryptedData(iv=None, ciphertext=encrypted_key, tag=None) serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context) iv = os.urandom(self.wrapping_algorithm.algorithm.iv_len) return encrypt( algorithm=self.wrapping_algorithm.algorithm, key=self._derived_wrapping_key, plaintext=plaintext_data_key, associated_data=serialized_encryption_context, iv=iv, )
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/wrapping_keys.py#L61-L87
aes encryption
python
def encrypt(self, text, recv_key='', template='', key_type=''): """ xmlsec encrypt --pubkey-pem pub-userkey.pem --session-key aes128-cbc --xml-data doc-plain.xml --output doc-encrypted.xml session-key-template.xml :param text: Text to encrypt :param recv_key: A file containing the receivers public key :param template: A file containing the XMLSEC template :param key_type: The type of session key to use :result: An encrypted XML text """ if not key_type: key_type = self.encrypt_key_type if not template: template = self.template return self.crypto.encrypt(text, recv_key, template, key_type)
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/sigver.py#L1319-L1336
aes encryption
python
def _encrypt(self, data, recipients, default_key=None, passphrase=None, armor=True, encrypt=True, symmetric=False, always_trust=True, output=None, throw_keyids=False, hidden_recipients=None, cipher_algo='AES256', digest_algo='SHA512', compress_algo='ZLIB'): """Encrypt the message read from the file-like object **data**. :param str data: The file or bytestream to encrypt. :param str recipients: The recipients to encrypt to. Recipients must be specified keyID/fingerprint. .. warning:: Care should be taken in Python2 to make sure that the given fingerprints for **recipients** are in fact strings and not unicode objects. :param str default_key: The keyID/fingerprint of the key to use for signing. If given, **data** will be encrypted *and* signed. :param str passphrase: If given, and **default_key** is also given, use this passphrase to unlock the secret portion of the **default_key** to sign the encrypted **data**. Otherwise, if **default_key** is not given, but **symmetric** is ``True``, then use this passphrase as the passphrase for symmetric encryption. Signing and symmetric encryption should *not* be combined when sending the **data** to other recipients, else the passphrase to the secret key would be shared with them. :param bool armor: If True, ascii armor the output; otherwise, the output will be in binary format. (Default: True) :param bool encrypt: If True, encrypt the **data** using the **recipients** public keys. (Default: True) :param bool symmetric: If True, encrypt the **data** to **recipients** using a symmetric key. See the **passphrase** parameter. Symmetric encryption and public key encryption can be used simultaneously, and will result in a ciphertext which is decryptable with either the symmetric **passphrase** or one of the corresponding private keys. :param bool always_trust: If True, ignore trust warnings on **recipients** keys. If False, display trust warnings. (default: True) :type output: str or file-like object :param output: The output file to write to. If not specified, the encrypted output is returned, and thus should be stored as an object in Python. For example: >>> import shutil >>> import gnupg >>> if os.path.exists("doctests"): ... shutil.rmtree("doctests") >>> gpg = gnupg.GPG(homedir="doctests") >>> key_settings = gpg.gen_key_input(key_type='RSA', ... key_length=1024, ... key_usage='ESCA', ... passphrase='foo') >>> key = gpg.gen_key(key_settings) >>> message = "The crow flies at midnight." >>> encrypted = str(gpg.encrypt(message, key.fingerprint)) >>> assert encrypted != message >>> assert not encrypted.isspace() >>> decrypted = str(gpg.decrypt(encrypted, passphrase='foo')) >>> assert not decrypted.isspace() >>> decrypted 'The crow flies at midnight.' :param bool throw_keyids: If True, make all **recipients** keyids be zero'd out in packet information. This is the same as using **hidden_recipients** for all **recipients**. (Default: False). :param list hidden_recipients: A list of recipients that should have their keyids zero'd out in packet information. :param str cipher_algo: The cipher algorithm to use. To see available algorithms with your version of GnuPG, do: :command:`$ gpg --with-colons --list-config ciphername`. The default **cipher_algo**, if unspecified, is ``'AES256'``. :param str digest_algo: The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: :command:`$ gpg --with-colons --list-config digestname`. The default, if unspecified, is ``'SHA512'``. :param str compress_algo: The compression algorithm to use. Can be one of ``'ZLIB'``, ``'BZIP2'``, ``'ZIP'``, or ``'Uncompressed'``. """ args = [] ## FIXME: GnuPG appears to ignore the --output directive when being ## programmatically driven. We'll handle the IO ourselves to fix this ## for now. output_filename = None if output: if getattr(output, 'fileno', None) is not None: ## avoid overwrite confirmation message if getattr(output, 'name', None) is not None: output_filename = output.name if os.path.exists(output.name): os.remove(output.name) #args.append('--output %s' % output.name) else: output_filename = output if os.path.exists(output): os.remove(output) #args.append('--output %s' % output) if armor: args.append('--armor') if always_trust: args.append('--always-trust') if cipher_algo: args.append('--cipher-algo %s' % cipher_algo) if compress_algo: args.append('--compress-algo %s' % compress_algo) if default_key: args.append('--sign') args.append('--default-key %s' % default_key) if digest_algo: args.append('--digest-algo %s' % digest_algo) ## both can be used at the same time for an encrypted file which ## is decryptable with a passphrase or secretkey. if symmetric: args.append('--symmetric') if encrypt: args.append('--encrypt') if throw_keyids: args.append('--throw-keyids') if len(recipients) >= 1: log.debug("GPG.encrypt() called for recipients '%s' with type '%s'" % (recipients, type(recipients))) if isinstance(recipients, (list, tuple)): for recp in recipients: if not _util._py3k: if isinstance(recp, unicode): try: assert _parsers._is_hex(str(recp)) except AssertionError: log.info("Can't accept recipient string: %s" % recp) else: self._add_recipient_string(args, hidden_recipients, str(recp)) continue ## will give unicode in 2.x as '\uXXXX\uXXXX' if isinstance(hidden_recipients, (list, tuple)): if [s for s in hidden_recipients if recp in str(s)]: args.append('--hidden-recipient %r' % recp) else: args.append('--recipient %r' % recp) else: args.append('--recipient %r' % recp) continue if isinstance(recp, str): self._add_recipient_string(args, hidden_recipients, recp) elif (not _util._py3k) and isinstance(recp, basestring): for recp in recipients.split('\x20'): self._add_recipient_string(args, hidden_recipients, recp) elif _util._py3k and isinstance(recp, str): for recp in recipients.split(' '): self._add_recipient_string(args, hidden_recipients, recp) ## ...and now that we've proven py3k is better... else: log.debug("Don't know what to do with recipients: %r" % recipients) result = self._result_map['crypt'](self) log.debug("Got data '%s' with type '%s'." % (data, type(data))) self._handle_io(args, data, result, passphrase=passphrase, binary=True) # Avoid writing raw encrypted bytes to terminal loggers and breaking # them in that adorable way where they spew hieroglyphics until reset: if armor: log.debug("\n%s" % result.data) if output_filename: log.info("Writing encrypted output to file: %s" % output_filename) with open(output_filename, 'wb') as fh: fh.write(result.data) fh.flush() log.info("Encrypted output written successfully.") return result
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L881-L1079
aes encryption
python
def aes_ecb_compare(self, key_handle, ciphertext, plaintext): """ AES ECB decrypt and then compare using a key handle. The comparison is done inside the YubiHSM so the plaintext is never exposed (well, except indirectionally when the provided plaintext does match). @warning: Please be aware of the known limitations of AES ECB mode before using it! @param key_handle: Key handle to use for AES ECB decryption @param plaintext: Data to decrypt @type key_handle: integer or string @type plaintext: string @returns: Match result @rtype: bool @see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare} """ return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare( \ self.stick, key_handle, ciphertext, plaintext).execute()
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L543-L563
aes encryption
python
def encrypt(self, password, kdf=None, iterations=None): ''' Generate a string with the encrypted key, as in :meth:`~eth_account.account.Account.encrypt`, but without a private key argument. ''' return self._publicapi.encrypt(self.privateKey, password, kdf=kdf, iterations=iterations)
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/signers/local.py#L51-L56
aes encryption
python
def aes_cbc_encrypt_data(symkey, iv, data, pad): # type: (bytes, bytes, bytes, bool) -> bytes """Encrypt data using AES CBC :param bytes symkey: symmetric key :param bytes iv: initialization vector :param bytes data: data to encrypt :param bool pad: pad data :rtype: bytes :return: encrypted data """ cipher = cryptography.hazmat.primitives.ciphers.Cipher( cryptography.hazmat.primitives.ciphers.algorithms.AES(symkey), cryptography.hazmat.primitives.ciphers.modes.CBC(iv), backend=cryptography.hazmat.backends.default_backend()).encryptor() if pad: return cipher.update(pkcs7_pad(data)) + cipher.finalize() else: return cipher.update(data) + cipher.finalize()
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/crypto.py#L211-L228
aes encryption
python
def encrypt(receiver_pubhex: str, msg: bytes) -> bytes: """ Encrypt with eth public key Parameters ---------- receiver_pubhex: str Receiver's ethereum public key hex string msg: bytes Data to encrypt Returns ------- bytes Encrypted data """ disposable_key = generate_key() receiver_pubkey = hex2pub(receiver_pubhex) aes_key = derive(disposable_key, receiver_pubkey) cipher_text = aes_encrypt(aes_key, msg) return disposable_key.public_key.format(False) + cipher_text
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/__init__.py#L6-L26
aes encryption
python
def encrypt_file(path, output, password=None): ''' Encrypt file with AES method and password. ''' if not password: password = PASSWORD_FILE query = 'openssl aes-128-cbc -salt -in {0} -out {1} -k {2}' with hide('output'): local(query.format(path, output, password)) os.remove(path)
https://github.com/yograterol/zoort/blob/ed6669ab945007c20a83f6d468856c4eb585c752/zoort.py#L680-L689
aes encryption
python
def encrypt(self, data, uid=None, cryptographic_parameters=None, iv_counter_nonce=None): """ Encrypt data using the specified encryption key and parameters. Args: data (bytes): The bytes to encrypt. Required. uid (string): The unique ID of the encryption key to use. Optional, defaults to None. cryptographic_parameters (dict): A dictionary containing various cryptographic settings to be used for the encryption. Optional, defaults to None. iv_counter_nonce (bytes): The bytes to use for the IV/counter/ nonce, if needed by the encryption algorithm and/or cipher mode. Optional, defaults to None. Returns: bytes: The encrypted data. bytes: The IV/counter/nonce used with the encryption algorithm, only if it was autogenerated by the server. Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input arguments are invalid Notes: The cryptographic_parameters argument is a dictionary that can contain the following key/value pairs: Keys | Value ------------------------------|----------------------------------- 'block_cipher_mode' | A BlockCipherMode enumeration | indicating the cipher mode to use | with the encryption algorithm. 'padding_method' | A PaddingMethod enumeration | indicating which padding method to | use with the encryption algorithm. 'hashing_algorithm' | A HashingAlgorithm enumeration | indicating which hashing algorithm | to use. 'key_role_type' | A KeyRoleType enumeration | indicating the intended use of the | associated cryptographic key. 'digital_signature_algorithm' | A DigitalSignatureAlgorithm | enumeration indicating which | digital signature algorithm to | use. 'cryptographic_algorithm' | A CryptographicAlgorithm | enumeration indicating which | encryption algorithm to use. 'random_iv' | A boolean indicating whether the | server should autogenerate an IV. 'iv_length' | An integer representing the length | of the initialization vector (IV) | in bits. 'tag_length' | An integer representing the length | of the authenticator tag in bytes. 'fixed_field_length' | An integer representing the length | of the fixed field portion of the | IV in bits. 'invocation_field_length' | An integer representing the length | of the invocation field portion of | the IV in bits. 'counter_length' | An integer representing the length | of the coutner portion of the IV | in bits. 'initial_counter_value' | An integer representing the | starting counter value for CTR | mode (typically 1). """ # Check input if not isinstance(data, six.binary_type): raise TypeError("data must be bytes") if uid is not None: if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") if cryptographic_parameters is not None: if not isinstance(cryptographic_parameters, dict): raise TypeError("cryptographic_parameters must be a dict") if iv_counter_nonce is not None: if not isinstance(iv_counter_nonce, six.binary_type): raise TypeError("iv_counter_nonce must be bytes") cryptographic_parameters = self._build_cryptographic_parameters( cryptographic_parameters ) # Encrypt the provided data and handle the results result = self.proxy.encrypt( data, uid, cryptographic_parameters, iv_counter_nonce ) status = result.get('result_status') if status == enums.ResultStatus.SUCCESS: return result.get('data'), result.get('iv_counter_nonce') else: raise exceptions.KmipOperationFailure( status, result.get('result_reason'), result.get('result_message') )
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/pie/client.py#L1042-L1146
aes encryption
python
def encrypt_password(self, email, password): """ Get the RSA key for the user and encrypt the users password :param email: steam account :param password: password for account :return: encrypted password """ res = self.session.http.get(self._get_rsa_key_url, params=dict(username=email, donotcache=self.donotcache)) rsadata = self.session.http.json(res, schema=self._rsa_key_schema) rsa = RSA.construct((rsadata["publickey_mod"], rsadata["publickey_exp"])) cipher = PKCS1_v1_5.new(rsa) return base64.b64encode(cipher.encrypt(password.encode("utf8"))), rsadata["timestamp"]
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugins/steam.py#L90-L102
aes encryption
python
def aes_obj(self, sec_key, encrypt_sec_key=True): """ 生成aes加密所需要的 ``key, iv`` .. warning:: 每个AES.new对象, 只能使用一次 :param sec_key: :type sec_key: str :param encrypt_sec_key: ``如果为true, 则md5加密 sec_key, 生成 key,iv, 否则直接使用 sec_key, 来作为key,iv`` :type encrypt_sec_key: bool :return: :rtype: """ # 使用 md5加密 key, 获取32个长度, 拆分为两个16长度作为 AES的 key, iv p = self.encrypt(sec_key) if encrypt_sec_key else sec_key key, iv = p[:self.bs], p[16:] return AES.new(helper.to_bytes(key), self.aes_mode, helper.to_bytes(iv))
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L61-L78
aes encryption
python
def encrypt(self, data): """ Encrypt the given data with cipher that is got from AES.cipher call. :param data: data to encrypt :return: bytes """ padding = self.mode().padding() if padding is not None: data = padding.pad(data, WAESMode.__data_padding_length__) return self.cipher().encrypt_block(data)
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/aes.py#L501-L511
aes encryption
python
def aes_cbc_pkcs7_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingPKCS7Key)
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L169-L208
aes encryption
python
def decrypt(self, text, appid): """对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文 """ try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception: return WXBizMsgCrypt_DecryptAES_Error, None try: pad = ord(plain_text[-1]) # 去掉补位字符串 #pkcs7 = PKCS7Encoder() #plain_text = pkcs7.encode(plain_text) # 去除16位随机字符串 content = plain_text[16:-pad] xml_len = socket.ntohl(struct.unpack("I", content[:4])[0]) xml_content = content[4:xml_len+4] from_appid = content[xml_len+4:] except Exception: return WXBizMsgCrypt_IllegalBuffer, None if from_appid != appid: return WXBizMsgCrypt_ValidateAppidOrCorpid_Error, None return 0, xml_content
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L167-L192
aes encryption
python
def _encrypt_xor(a, b, aes): """ Returns encrypt(a ^ b). """ a = unhexlify("%0.32x" % (int((a), 16) ^ int(hexlify(b), 16))) return aes.encrypt(a)
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/bip38.py#L40-L43
aes encryption
python
def aes_cbc_decrypt_data(symkey, iv, encdata, unpad): # type: (bytes, bytes, bytes, bool) -> bytes """Decrypt data using AES CBC :param bytes symkey: symmetric key :param bytes iv: initialization vector :param bytes encdata: data to decrypt :param bool unpad: unpad data :rtype: bytes :return: decrypted data """ cipher = cryptography.hazmat.primitives.ciphers.Cipher( cryptography.hazmat.primitives.ciphers.algorithms.AES(symkey), cryptography.hazmat.primitives.ciphers.modes.CBC(iv), backend=cryptography.hazmat.backends.default_backend()).decryptor() decrypted = cipher.update(encdata) + cipher.finalize() if unpad: return pkcs7_unpad(decrypted) else: return decrypted
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/crypto.py#L190-L208
aes encryption
python
def _decrypt(self, fp, password=None): """ Internal decryption function Uses either the password argument for the decryption, or, if not supplied, the password field of the object :param fp: a file object or similar which supports the readline and read methods :rtype: Proxy """ if AES is None: raise ImportError("PyCrypto required") if password is None: password = self.password if password is None: raise ValueError( "Password need to be provided to extract encrypted archives") # read the PBKDF2 parameters # salt user_salt = fp.readline().strip() user_salt = binascii.a2b_hex(user_salt) # checksum salt ck_salt = fp.readline().strip() ck_salt = binascii.a2b_hex(ck_salt) # hashing rounds rounds = fp.readline().strip() rounds = int(rounds) # encryption IV iv = fp.readline().strip() iv = binascii.a2b_hex(iv) # encrypted master key master_key = fp.readline().strip() master_key = binascii.a2b_hex(master_key) # generate key for decrypting the master key user_key = PBKDF2(password, user_salt, dkLen=256 // 8, count=rounds) # decrypt the master key and iv cipher = AES.new(user_key, mode=AES.MODE_CBC, IV=iv) master_key = bytearray(cipher.decrypt(master_key)) # format: <len IV: 1 byte><IV: n bytes><len key: 1 byte><key: m bytes><len checksum: 1 byte><checksum: k bytes> # get IV l = master_key.pop(0) master_iv = bytes(master_key[:l]) master_key = master_key[l:] # get key l = master_key.pop(0) mk = bytes(master_key[:l]) master_key = master_key[l:] # get checksum l = master_key.pop(0) master_ck = bytes(master_key[:l]) # double encode utf8 utf8mk = self.encode_utf8(mk) # calculate checksum by using PBKDF2 calc_ck = PBKDF2(utf8mk, ck_salt, dkLen=256//8, count=rounds) assert calc_ck == master_ck # install decryption key cipher = AES.new(mk, mode=AES.MODE_CBC, IV=master_iv) off = fp.tell() fp.seek(0, 2) length = fp.tell() - off fp.seek(off) if self.stream: # decryption transformer for Proxy class def decrypt(data): data = bytearray(cipher.decrypt(data)) if fp.tell() - off >= length: # check padding (PKCS#7) pad = data[-1] assert data.endswith(bytearray([pad] * pad)), "Expected {!r} got {!r}".format(bytearray([pad] * pad), data[-pad:]) data = data[:-pad] return data return Proxy(decrypt, fp, cipher.block_size) else: data = bytearray(cipher.decrypt(fp.read())) pad = data[-1] assert data.endswith(bytearray([pad] * pad)), "Expected {!r} got {!r}".format(bytearray([pad] * pad), data[-pad:]) data = data[:-pad] return io.BytesIO(data)
https://github.com/bluec0re/android-backup-tools/blob/e2e0d95e56624c1a99a176df9e307398e837d908/android_backup/android_backup.py#L145-L236
aes encryption
python
def encrypt(self, text, appid): """对明文进行加密 @param text: 需要加密的明文 @return: 加密得到的字符串 """ # 16位随机字符串添加到明文开头 text = self.get_random_str() + struct.pack( "I", socket.htonl(len(text))) + text + appid # 使用自定义的填充方式对明文进行补位填充 pkcs7 = PKCS7Encoder() text = pkcs7.encode(text) # 加密 cryptor = AES.new(self.key, self.mode, self.key[:16]) try: ciphertext = cryptor.encrypt(text) # 使用BASE64对加密后的字符串进行编码 return WXBizMsgCrypt_OK, base64.b64encode(ciphertext) except Exception: return WXBizMsgCrypt_EncryptAES_Error, None
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L147-L165
aes encryption
python
def encrypt(self, keys=None, cek="", iv="", **kwargs): """ Encrypt a payload :param keys: A set of possibly usable keys :param cek: Content master key :param iv: Initialization vector :param kwargs: Extra key word arguments :return: Encrypted message """ _alg = self["alg"] # Find Usable Keys if keys: keys = self.pick_keys(keys, use="enc") else: keys = self.pick_keys(self._get_keys(), use="enc") if not keys: logger.error(KEY_ERR.format(_alg)) raise NoSuitableEncryptionKey(_alg) # Determine Encryption Class by Algorithm if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]: encrypter = JWE_RSA(self.msg, **self._dict) elif _alg.startswith("A") and _alg.endswith("KW"): encrypter = JWE_SYM(self.msg, **self._dict) else: # _alg.startswith("ECDH-ES"): encrypter = JWE_EC(**self._dict) cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup( self.msg, key=keys[0], **self._dict) kwargs["encrypted_key"] = encrypted_key kwargs["params"] = params if cek: kwargs["cek"] = cek if iv: kwargs["iv"] = iv for key in keys: if isinstance(key, SYMKey): _key = key.key elif isinstance(key, ECKey): _key = key.public_key() else: # isinstance(key, RSAKey): _key = key.public_key() if key.kid: encrypter["kid"] = key.kid try: token = encrypter.encrypt(key=_key, **kwargs) self["cek"] = encrypter.cek if 'cek' in encrypter else None except TypeError as err: raise err else: logger.debug( "Encrypted message using key with kid={}".format(key.kid)) return token
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe.py#L64-L124
aes encryption
python
def encrypt(self, plaintext, nonce, encoder=encoding.RawEncoder): """ Encrypts the plaintext message using the given `nonce` and returns the ciphertext encoded with the encoder. .. warning:: It is **VITALLY** important that the nonce is a nonce, i.e. it is a number used only once for any given key. If you fail to do this, you compromise the privacy of the messages encrypted. :param plaintext: [:class:`bytes`] The plaintext message to encrypt :param nonce: [:class:`bytes`] The nonce to use in the encryption :param encoder: The encoder to use to encode the ciphertext :rtype: [:class:`nacl.utils.EncryptedMessage`] """ if len(nonce) != self.NONCE_SIZE: raise ValueError("The nonce must be exactly %s bytes long" % self.NONCE_SIZE) ciphertext = libnacl.crypto_box_afternm( plaintext, nonce, self._shared_key, ) encoded_nonce = encoder.encode(nonce) encoded_ciphertext = encoder.encode(ciphertext) return EncryptedMessage._from_parts( encoded_nonce, encoded_ciphertext, encoder.encode(nonce + ciphertext), )
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L357-L388
aes encryption
python
def encryption_cipher(self): """ Returns the name of the symmetric encryption cipher to use. The key length can be retrieved via the .key_length property to disabiguate between different variations of TripleDES, AES, and the RC* ciphers. :return: A unicode string from one of the following: "rc2", "rc5", "des", "tripledes", "aes" """ encryption_algo = self['algorithm'].native if encryption_algo[0:7] in set(['aes128_', 'aes192_', 'aes256_']): return 'aes' if encryption_algo in set(['des', 'rc2', 'rc5']): return encryption_algo if encryption_algo == 'tripledes_3key': return 'tripledes' if encryption_algo == 'pbes2': return self['parameters']['encryption_scheme'].encryption_cipher if encryption_algo.find('.') == -1: return { 'pbes1_md2_des': 'des', 'pbes1_md5_des': 'des', 'pbes1_md2_rc2': 'rc2', 'pbes1_md5_rc2': 'rc2', 'pbes1_sha1_des': 'des', 'pbes1_sha1_rc2': 'rc2', 'pkcs12_sha1_rc4_128': 'rc4', 'pkcs12_sha1_rc4_40': 'rc4', 'pkcs12_sha1_tripledes_3key': 'tripledes', 'pkcs12_sha1_tripledes_2key': 'tripledes', 'pkcs12_sha1_rc2_128': 'rc2', 'pkcs12_sha1_rc2_40': 'rc2', }[encryption_algo] raise ValueError(unwrap( ''' Unrecognized encryption algorithm "%s" ''', encryption_algo ))
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/algos.py#L973-L1019
aes encryption
python
def encrypt_with_ad(self, ad: bytes, plaintext: bytes) -> bytes: """ If k is non-empty returns ENCRYPT(k, n++, ad, plaintext). Otherwise returns plaintext. :param ad: bytes sequence :param plaintext: bytes sequence :return: ciphertext bytes sequence """ if self.n == MAX_NONCE: raise NoiseMaxNonceError('Nonce has depleted!') if not self.has_key(): return plaintext ciphertext = self.cipher.encrypt(self.k, self.n, ad, plaintext) self.n = self.n + 1 return ciphertext
https://github.com/plizonczyk/noiseprotocol/blob/d0ec43c7c00b429119be3947266f345ccb97dccf/noise/state.py#L41-L57
aes encryption
python
async def encrypt(self, message: bytes, authn: bool = False, recip: str = None) -> bytes: """ Encrypt plaintext for owner of DID or verification key, anonymously or via authenticated encryption scheme. If given DID, first check wallet and then pool for corresponding verification key. Raise WalletState if the wallet is closed. Given a recipient DID not in the wallet, raise AbsentPool if the instance has no pool or ClosedPool if its pool is closed. :param message: plaintext, as bytes :param authn: whether to use authenticated encryption scheme :param recip: DID or verification key of recipient, None for anchor's own :return: ciphertext, as bytes """ LOGGER.debug('BaseAnchor.encrypt >>> message: %s, authn: %s, recip: %s', message, authn, recip) if not self.wallet.handle: LOGGER.debug('BaseAnchor.encrypt <!< Wallet %s is closed', self.name) raise WalletState('Wallet {} is closed'.format(self.name)) rv = await self.wallet.encrypt(message, authn, await self._verkey_for(recip)) LOGGER.debug('BaseAnchor.auth_encrypt <<< %s', rv) return rv
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/base.py#L747-L771
aes encryption
python
def encrypt_state_m(self, plaintext_in, key_in, reset): """ Builds a multiple cycle AES Encryption state machine circuit :param reset: a one bit signal telling the state machine to reset and accept the current plaintext and key :return ready, cipher_text: ready is a one bit signal showing that the encryption result (cipher_text) has been calculated. """ if len(key_in) != len(plaintext_in): raise pyrtl.PyrtlError("AES key and plaintext should be the same length") plain_text, key = (pyrtl.Register(len(plaintext_in)) for i in range(2)) key_exp_in, add_round_in = (pyrtl.WireVector(len(plaintext_in)) for i in range(2)) counter = pyrtl.Register(4, 'counter') round = pyrtl.WireVector(4, 'round') counter.next <<= round sub_out = self._sub_bytes(plain_text) shift_out = self._shift_rows(sub_out) mix_out = self._mix_columns(shift_out) key_out = self._key_expansion(key, counter) add_round_out = self._add_round_key(add_round_in, key_exp_in) with pyrtl.conditional_assignment: with reset == 1: round |= 0 key_exp_in |= key_in # to lower the number of cycles plain_text.next |= add_round_out key.next |= key_in add_round_in |= plaintext_in with counter == 10: # keep everything the same round |= counter plain_text.next |= plain_text with pyrtl.otherwise: # running through AES round |= counter + 1 key_exp_in |= key_out plain_text.next |= add_round_out key.next |= key_out with counter == 9: add_round_in |= shift_out with pyrtl.otherwise: add_round_in |= mix_out ready = (counter == 10) return ready, plain_text
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/aes.py#L78-L125
aes encryption
python
def _authenticate(self): ''' Authenticate with the master, this method breaks the functional paradigm, it will update the master information from a fresh sign in, signing in can occur as often as needed to keep up with the revolving master AES key. :rtype: Crypticle :returns: A crypticle used for encryption operations ''' acceptance_wait_time = self.opts['acceptance_wait_time'] acceptance_wait_time_max = self.opts['acceptance_wait_time_max'] if not acceptance_wait_time_max: acceptance_wait_time_max = acceptance_wait_time creds = None channel = salt.transport.client.AsyncReqChannel.factory(self.opts, crypt='clear', io_loop=self.io_loop) try: error = None while True: try: creds = yield self.sign_in(channel=channel) except SaltClientError as exc: error = exc break if creds == 'retry': if self.opts.get('detect_mode') is True: error = SaltClientError('Detect mode is on') break if self.opts.get('caller'): # We have a list of masters, so we should break # and try the next one in the list. if self.opts.get('local_masters', None): error = SaltClientError('Minion failed to authenticate' ' with the master, has the ' 'minion key been accepted?') break else: print('Minion failed to authenticate with the master, ' 'has the minion key been accepted?') sys.exit(2) if acceptance_wait_time: log.info( 'Waiting %s seconds before retry.', acceptance_wait_time ) yield tornado.gen.sleep(acceptance_wait_time) if acceptance_wait_time < acceptance_wait_time_max: acceptance_wait_time += acceptance_wait_time log.debug( 'Authentication wait time is %s', acceptance_wait_time ) continue break if not isinstance(creds, dict) or 'aes' not in creds: if self.opts.get('detect_mode') is True: error = SaltClientError('-|RETRY|-') try: del AsyncAuth.creds_map[self.__key(self.opts)] except KeyError: pass if not error: error = SaltClientError('Attempt to authenticate with the salt master failed') self._authenticate_future.set_exception(error) else: key = self.__key(self.opts) AsyncAuth.creds_map[key] = creds self._creds = creds self._crypticle = Crypticle(self.opts, creds['aes']) self._authenticate_future.set_result(True) # mark the sign-in as complete # Notify the bus about creds change if self.opts.get('auth_events') is True: event = salt.utils.event.get_event(self.opts.get('__role'), opts=self.opts, listen=False) event.fire_event( {'key': key, 'creds': creds}, salt.utils.event.tagify(prefix='auth', suffix='creds') ) finally: channel.close()
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/crypt.py#L582-L661
aes encryption
python
def encrypt(passwd): """ Encrypts the incoming password after adding some salt to store it in the database. @param passwd: password portion of user credentials @type passwd: string @returns: encrypted/salted string """ m = sha1() salt = hexlify(os.urandom(salt_len)) m.update(unicode2bytes(passwd) + salt) crypted = bytes2unicode(salt) + m.hexdigest() return crypted
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/process/users/users.py#L155-L169