async def dump_method(cache: List[odict]): """Pads and encrypts the contents of a message""" args = [] for ord_d in cache: if ord_d["content"]: message = Padding.pad(bytes(ord_d["content"], "utf-8"), 16) encr_msg = self.aes.encrypt(message) else: encr_msg = "No message" ord_d["content"] = encr_msg args.append(list(ord_d.values())) # Loop end # =================================================== # | Example of database dumping, with postgresql # =================================================== # query = """ # INSERT INTO messagelog(messageid, authorid, guildid, channelid, date, content) # VALUES($1, $2, $3, $4, $5, $6) # ON CONFLICT(messageid, authorid) # DO NOTHING""" # # # here self.bot.db is an pool from -> asyncpg.create_pool() # async with self.bot.db.acquire() as connection: # async with connection.transaction(): # await self.bot.db.executemany(query, args) # =================================================== # Clear cache for new messages cache[:] = []
def encrypt(pass_phrase, data): """ Encrypt data using a pass phrase :param pass_phrase: Pass phrase to encrypt data with :type pass_phrase: String :param data: Data to encrypt :type data: String :return: Formatted string that contains salt, iv and encrypted message :rtype: String """ mode = AES.MODE_CBC block_size = AES.block_size salt = get_random_bytes(8) key = PBKDF2(pass_phrase, salt) body = Padding.pad(data.encode('utf-8'), block_size) initialization_vector = get_random_bytes(16) cipher = AES.new(key, mode, initialization_vector) # Now reassign salt, iv and body with their base64 encoded counterparts salt = b64encode(salt).decode('utf-8') initialization_vector = b64encode(initialization_vector).decode('utf-8') body = b64encode(cipher.encrypt(body)).decode('utf-8') return '{0}.{1}.{2}'.format(salt, initialization_vector, body)
def encryption(data): crypt = DES.new(b'12345678', DES.MODE_ECB) content = json.dumps(data, separators=(',', ':')) content = Padding.pad(content.encode('utf8'), 8, 'pkcs7') content = crypt.encrypt(content) content = base64.b64encode(content) return content
def encrypt_json(raw_data, secret_bytes_key, cipher_type='AES'): # TODO: add salt to raw_data padded_data = Padding.pad( data_to_pad=raw_data, block_size=AES.block_size, ) if cipher_type == 'AES': cipher = AES.new( key=secret_bytes_key, mode=AES.MODE_CBC, ) elif cipher_type == 'DES3': cipher = DES3.new( key=secret_bytes_key, mode=DES3.MODE_CBC, ) else: raise Exception('unsupported cipher type') ct_bytes = cipher.encrypt(padded_data) dct = { 'iv': base64.b64encode(cipher.iv).decode('utf-8'), 'ct': base64.b64encode(ct_bytes).decode('utf-8'), } encrypted_data = serialization.DictToBytes(dct, encoding='utf-8') return encrypted_data
def msl_encrypt(msl_session, plaintext): """ msl_encrypt() @param msl_session: Dict of msl_session created by the client upon initialization @param plaintext: Plaintext to encrypt @return: JSON byte string of encryption envelope """ cbc_iv = os.urandom(16) encryption_envelope = { 'keyid': '%s_%s' % (msl_session['esn'], msl_session['session_keys']['sequence_number']), 'sha256': 'AA==', 'iv': base64.b64encode(cbc_iv).decode('utf8') } plaintext = Padding.pad(plaintext.encode('utf8'), 16) cipher = AES.new(msl_session['session_keys']['encryption_key'], AES.MODE_CBC, cbc_iv) ciphertext = cipher.encrypt(plaintext) encryption_envelope['ciphertext'] = base64.b64encode(ciphertext).decode( 'utf8') return json.dumps(encryption_envelope).encode('utf8')
def encrypt(plaintext, key, keylen=KEYLEN): """Encrypt bytes using AES-CBC with keys of length `keylen` (defaults to KEYLEN: 256 bits). Key is passed in KDF `PBKDF2` in order to protect weak keys against brute force attacks. @param plaintext: Data to be encrypted. @type plaintext: bytes @param key: Encryption passphrase. @type key: str, bytes @param keylen: Length of the key to use in bytes. Can be either 16, 24 or 32. @type keylen: str, bytes @return: The produced ciphertext. @rtype : bytes @raise ValueError: Incorrect padding. Happens if passphrase is incorrect. """ salt = Random.new().read(AES.block_size) iv = Random.new().read(AES.block_size) key = KDF.PBKDF2(key, salt, dkLen=keylen) plaintext = Padding.pad(plaintext, AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv=iv) return base64.b64encode(salt + iv + cipher.encrypt(plaintext))
def encrypt_data(self, login_id, login_password, account_password, certificate_password, given_key=None, file_name=None): plain_data = ';'.join((login_id, login_password, account_password, certificate_password)) if file_name is not None: self.file_name = file_name # key setting random = Random.new() raw_key = given_key if raw_key is None: raw_key = self.raw_key set_key = self.set_key(raw_key) iv = random.read(AES.block_size) encoded_key = set_key.encode() key = strxor.strxor(encoded_key, iv) # Encryption encoded_data = plain_data.encode() padded_data = Padding.pad(encoded_data, AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted_data = cipher.encrypt(padded_data) # File writing with open(self.file_name, 'wb') as file: file.write(iv) file.write(encrypted_data)
def _encode(self, payload_data, con, path): payload_data = CryptoPadding.pad(payload_data, 16) cipher = self.get_cipher( con.master_key, con._.header.value.dynamic_header.encryption_iv.data) payload_data = cipher.encrypt(payload_data) return payload_data
def encrypt_to_json(raw_data, secret_16bytes_key): # not in use at the moment cipher = AES.new(secret_16bytes_key, AES.MODE_CBC) ct_bytes = cipher.encrypt(Padding.pad(raw_data, AES.block_size)) iv = base64.b64encode(cipher.iv).decode('utf-8') ct = base64.b64encode(ct_bytes).decode('utf-8') result = json.dumps({'iv':iv, 'ct':ct, }, separators=(',', ':'), ) return result
def save_data(data, pin): raw = bytes(Padding.pad(data_to_pad=json.dumps(data).encode('utf-8'), block_size=16)) iv = '\x00' * 16 cipher = AES.new((str(pin) + str(pin) + str(pin) + str(pin)).encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8')) encrypted_data = base64.b64encode(cipher.encrypt(raw)).decode('utf-8') file = open('NFAuthentication.key', 'w') file.write(encrypted_data) file.close()
def encrypt(raw_data, secret_16bytes_key): cipher = AES.new( key=secret_16bytes_key, mode=AES.MODE_CBC, ) ct_bytes = cipher.encrypt(Padding.pad(raw_data, AES.block_size)) output_data = dict(iv=cipher.iv, ct=ct_bytes) result = serialization.ObjectToString(output_data) return result
def encrypt_credential_v1(self, raw): if sys.version_info < (3, 0): raw = bytes(raw) else: raw = bytes(raw, 'utf-8') raw = bytes(Padding.pad(data_to_pad=raw, block_size=32)) iv = Random.new().read(AES.block_size) cipher = AES.new(self.get_device_id_v1(), AES.MODE_CBC, iv) return Util.base64enc(iv + cipher.encrypt(raw))
def encrypt(self) -> (bytes, bytes): """ Encrypts input text with input key and nonce using cipher specified on the instance and generates a tag that can be used to verify message integrity Returns a tuple with the encrypted text, hash for checking integrity, and nonce """ ciphertext, tag = self.set_key(self.nonce).encrypt_and_digest(Padding.pad(bytes(self.text, "utf-8"), 16)) return ciphertext, tag
def encrypt_payload(plain_text, key): """Encrypts and returns cryptext given the plain text and key :param str plain_text: the plain text to be encrypted :param str key: The key, which is used for AES encryption :return: encrypted text """ key = key.encode("utf-8") crypt = AES.new(key, AES.MODE_CBC, iv=key) return binascii.hexlify( crypt.encrypt(Padding.pad(plain_text.encode("utf-8"), PADDING_OFFSET)))
def encode(self, raw): """ Encodes data :param data: Data to be encoded :type data: str :returns: string -- Encoded data """ raw = bytes(Padding.pad(data_to_pad=raw, block_size=self.bs)) iv = Random.new().read(AES.block_size) cipher = AES.new(self.crypt_key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
def authenticated_encrypt(aes_key, hmac_key, data): data = Padding.pad(data, AES.block_size, style='pkcs7') iv = Random.new().read(AES.block_size) # create random IV ciphertext = iv + AES.new(aes_key, AES.MODE_CBC, iv).encrypt( data.encode('utf-8')) # encrypt the data using AES in CBC # tag the encrypted data using HMAC-SHA256 hmac = HMAC.new(hmac_key, digestmod=SHA256) hmac.update(ciphertext) tag = hmac.hexdigest() return base64.b64encode(ciphertext + tag)
def get_cipherheader(epochtime, token, data): # cipherMethod: DES/CBC/PKCS7Padding json_dumps = json.dumps(data, ensure_ascii=False) md5_hash_code = hashlib.md5((json_dumps + token).encode()).hexdigest() base58_hash_code = base58.b58encode(md5_hash_code) key_iv = ( # 时间戳逆序取5位并作为时间戳字串索引再次取值,最后拼接"000" "".join([epochtime[int(i)] for i in epochtime[::-1][:5]]) + "000").encode() cipher = DES.new(key_iv, DES.MODE_CBC, key_iv) cipherText = cipher.encrypt( Padding.pad(base58_hash_code, DES.block_size, style="pkcs7")) return base64.b64encode(cipherText)
def encrypt_json(raw_data, secret_16bytes_key): # TODO: add salt to raw_data cipher = AES.new( key=secret_16bytes_key, mode=AES.MODE_CBC, ) ct_bytes = cipher.encrypt(Padding.pad(raw_data, AES.block_size)) dct = { 'iv': base64.b64encode(cipher.iv).decode('utf-8'), 'ct': base64.b64encode(ct_bytes).decode('utf-8'), } raw = serialization.DictToBytes(dct) return raw
def aes_encrypt(text, key): """ 还原了简单的aes加密,ECB模式, :param text: str待加密的字符串 :param key: str加密key :return: str密文结果 """ aes = AES.new(key.encode(), AES.MODE_ECB) text_b = text.encode() pad_text = Padding.pad(text_b, AES.block_size, style='pkcs7') encrypt_text = aes.encrypt(pad_text) encrypt_text = base64.b64encode(encrypt_text).decode() return encrypt_text
def encrypt(self, plaintext: str): padded_plaintext = Padding.pad( data_to_pad=plaintext.encode("utf-8"), block_size=AES.block_size ) iv = Random.new().read(AES.block_size) cipher = AES.new( key=self.key, mode=AES.MODE_CBC, iv=iv ) ciphertext = cipher.encrypt(padded_plaintext) return urlsafe_b64encode(iv + ciphertext).decode("utf-8")
def create_admin_profile(manager: services.EcbProfileManager) -> bytes: # Assume the attacker knows: # 1. AES encryption is being used. # 2. The profile format is [email protected]&uid=10&role=user. # # This isn't really a common scenario, but it saves a lot of boilerplate # around brute-forcing block sizes and offsets. I think this is what the # authors probably intended. magic_block = Padding.pad(b"admin", AES.block_size) email1 = "A" * (AES.block_size - len("email=")) + magic_block.decode() email2 = "A" * (2 * AES.block_size - len("email=") - len("&uid=10&role=")) profile1 = manager.profile_for(email1) profile2 = manager.profile_for(email2) # This is the cut-and-paste step. return profile2[:-AES.block_size] + profile1[AES.block_size:2 * AES.block_size]
def encrypt(self, plain, nonce=None): plain_padded = Padding.pad(plain.encode('utf-8'), block_size=16) if nonce is None: nonce = get_random_bytes(16).hex() self.__input_validator.check_type(nonce, str) if not (len(nonce) == 32 and set(nonce).issubset(set('0123456789abcdefABCDEF'))): raise ValueError('Invalid nonce. expected a 16-byte hex string. Got {}.'.format(nonce)) cipher = AES.new(bytes.fromhex(self.__key), mode=AES.MODE_EAX, nonce=bytes.fromhex(nonce)) ciphertext = cipher.encrypt(plain_padded) ciphertext = ciphertext.hex() nonce = cipher.nonce.hex() return ciphertext, nonce
def encrypt(string, key): """ Encrypt a string Args: param string: String to encrypt param key: Encryption key Returns: Base 64 encoded string """ string = Padding.pad(string.encode('utf8'), AES.block_size) key = hashlib.sha256(key.encode('utf8')).digest() cipher = AES.new(key, AES.MODE_CBC) ciphertext = cipher.encrypt(string) hash = hmac.new(key, ciphertext, digestmod=hashlib.sha256).digest() return base64.b64encode(cipher.iv + hash + ciphertext)
def encrypt(password, data): # Use the function defined above to get key and initialization vector # from our password string key, initialization_vector = AESCipher.EVP_BytesToKey( password.encode('latin1')) # Create a new AES cipher aes = AES.new(key, AES.MODE_CBC, iv=initialization_vector) # Pad our data using the PKCS#7 padding algorithm padded_data = Padding.pad(data.encode('utf-8'), 16, style='pkcs7') # Encrypt the padded data encrypted = aes.encrypt(padded_data) # Return converted bytestring to hex values return encrypted.hex()
def encrypt_credential(raw): """ Encodes data :param data: Data to be encoded :type data: str :returns: string -- Encoded data """ # pylint: disable=invalid-name,import-error import base64 from Cryptodome import Random from Cryptodome.Cipher import AES from Cryptodome.Util import Padding raw = bytes(Padding.pad(data_to_pad=raw, block_size=__BLOCK_SIZE__)) iv = Random.new().read(AES.block_size) cipher = AES.new(__crypt_key(), AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
def encrypt_json(raw_data, secret_16bytes_key): # TODO: add salt to raw_data padded_data = Padding.pad( data_to_pad=raw_data, block_size=AES.block_size, ) cipher = AES.new( key=secret_16bytes_key, mode=AES.MODE_CBC, ) ct_bytes = cipher.encrypt(padded_data) dct = { 'iv': base64.b64encode(cipher.iv).decode('utf-8'), 'ct': base64.b64encode(ct_bytes).decode('utf-8'), } encrypted_data = serialization.DictToBytes(dct, encoding='utf-8') return encrypted_data
def encrypt(self, sender, recipient, plain_text): """ Generates an AES encrypted cipher Uses MAC, then Encrypt model Padded with PCKS-7 Hash is the string ":sender:recipient" with sender and recipient as in the function parameter IV is generated at random Block size is 16 Bytes [same as PyCrypto] """ hashed_pt = plain_text + self.genHash(sender, recipient) hashed_bytes = hashed_pt.encode() # str to bytes cipher = AES.new(self.key, AES.MODE_CBC) # IV is generated randomly # if not specified ct_bytes = cipher.encrypt(Padding.pad(hashed_bytes, AES.block_size)) cipher_text = b16encode(cipher.iv) + b16encode(ct_bytes) return cipher_text.decode()
def encrypt(self, plaintext, esn): """ Encrypt the given Plaintext with the encryption key :param plaintext: :return: Serialized JSON String of the encryption Envelope """ init_vector = get_random_bytes(16) cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector) encryption_envelope = { 'ciphertext': '', 'keyid': '_'.join((esn, str(self.sequence_number))), 'sha256': 'AA==', 'iv': base64.standard_b64encode(init_vector) } encryption_envelope['ciphertext'] = base64.standard_b64encode( cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16))) return json.dumps(encryption_envelope)
def __encrypt(self, plaintext): """ Encrypt the given Plaintext with the encryption key :param plaintext: :return: Serialized JSON String of the encryption Envelope """ iv = get_random_bytes(16) encryption_envelope = { 'ciphertext': '', 'keyid': self.esn + '_' + str(self.sequence_number), 'sha256': 'AA==', 'iv': base64.standard_b64encode(iv) } # Padd the plaintext plaintext = Padding.pad(plaintext, 16) # Encrypt the text cipher = AES.new(self.encryption_key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(plaintext) encryption_envelope['ciphertext'] = base64.standard_b64encode(ciphertext) return json.dumps(encryption_envelope)
async def log_message(self, msg): msg_cont = f"{msg.content}" for attach in msg.attachments: msg_cont += f" - {attach.url}" if not msg_cont: msg_cont = "<Attachement not saved>" b_reason = Padding.pad(bytes(msg_cont, "utf-8"), 16) encrypted_msg = self.aes.encrypt(b_reason) date = datetime.datetime.utcnow() self.bot.msg_log.append({ "id": msg.id, "author": msg.author.id, "channel": msg.channel.id, "guild": msg.guild.id, "msg": encrypted_msg, "date": date })
def encrypt(self, data, esn, sequence_number): """ Encrypt the given Plaintext with the encryption key :param plaintext: :return: Serialized JSON String of the encryption Envelope """ iv = get_random_bytes(16) encryption_envelope = { 'ciphertext': '', 'keyid': esn + '_' + str(sequence_number), 'sha256': 'AA==', 'iv': base64.standard_b64encode(iv) } # Padd the plaintext plaintext = Padding.pad(data, 16) # Encrypt the text cipher = AES.new(self.encryption_key, AES.MODE_CBC, iv) citext = cipher.encrypt(plaintext) encryption_envelope['ciphertext'] = base64.standard_b64encode(citext) return encryption_envelope;