def test_aes(ctx): m = swig.opa_math_common_swig c = swig.opa_crypto_swig BS = 16 for i in range(100): key = os.urandom(BS) a = os.urandom(random.randint(0, BS - 1)) a1_pad = Padding.pad(a, BS) a2_pad = c.pkcs7(a, BS) c1 = AES.new(key, AES.MODE_ECB).encrypt(a1_pad) c2 = c.Aes(key, True).encrypt_raw(a2_pad) print(c1) print(c2) assert c1 == c2 for i in range(100): print(i) key = os.urandom(BS) a = os.urandom(random.randint(60, 100)) a1_pad = Padding.pad(a, BS) a2_pad = c.pkcs7(a, BS) c1 = AES.new(key, AES.MODE_ECB).encrypt(a1_pad) c2 = c.Aes(key, True).encrypt_ecb(a2_pad) print(c1) print(c2) assert c1 == c2 m2_pad = c.Aes(key, False).decrypt_ecb(c2) m2, ok = c.rpkcs7(m2_pad, BS) assert c1 == c2 print(m2, a, m2_pad) assert m2 == a for i in range(100): iv = os.urandom(BS) print(i) key = os.urandom(BS) a = os.urandom(random.randint(60, 100)) a1_pad = Padding.pad(a, BS) a2_pad = c.pkcs7(a, BS) c1 = AES.new(key, AES.MODE_CBC, iv=iv).encrypt(a1_pad) c2 = c.Aes(key, True).encrypt_cbc(a2_pad, iv) print(c1) print(c2) assert c1 == c2 m2_pad = c.Aes(key, False).decrypt_cbc(c2, iv) m2, ok = c.rpkcs7(m2_pad, BS) assert c1 == c2 print(m2, a, m2_pad) assert m2 == a
def encrypt(self, raw, key, iv): enc_key = SHA256.new(key.encode()).digest() cipher = AES.new(enc_key, self.mode, iv) if type(raw) == str: data = Padding.pad(raw.encode('utf-8'), AES.block_size, self.padding_alg) else: data = Padding.pad(raw, AES.block_size, self.padding_alg) bin_encrypted = cipher.encrypt(data) return bin_encrypted
def protect_firmware(infile, outfile, version, message): with open(infile, 'rb') as f: #gets firmware fw = f.read() metadata = struct.pack( "<HH", version, len(fw)) #packs metadata: version, length of unencrypted firmware fw = fw + message.encode() + b'\00' #adds message to end of firmware with open("secret_build_output.txt", 'rb') as sec_output: aes_key = sec_output.read(16) #get symmetric key rsa_key = RSA.import_key(sec_output.read()) #get private key cipher = AES.new(aes_key, AES.MODE_CBC) #creates AES object encrypted_fw = cipher.encrypt(Padding.pad( fw, AES.block_size)) #encrypts firmware metadata += struct.pack( "<H", len(encrypted_fw)) #adds the length of encrypted firmware to metadata hashed_fw = SHA256.new( data=metadata + cipher.iv + encrypted_Fw) #hashes the metadata, IV, and encrypted firmware signature = pkcs1_15.new(rsa_key).sign( hashed_fw) #signs the hashed firmware fw_blob = signature + metadata + cipher.iv + encrypted_fw #creates blob to be sent to bootloader with open(outfile, "w+b") as out: #writes firmware blob to another file out.write(fw_blob) return 0
def encrypt(self, input): input = Padding.pad(input, self.block_size) output = b'' for i in range(len(input) // self.block_size): output += self.cypher.encrypt(input[i * self.block_size:(i + 1) * self.block_size]) return output
def encriptarAES(mensaje, clave, iv): # Ajustamos el mensaje a 16 bytes mensaje = Padding.pad(mensaje, 16) # Devolvemos el vector de inicializacion unido con el mensaje encriptado return AES.new(clave, AES.MODE_CBC, iv).encrypt(mensaje)
def _encrypt_data(self, data): """Make data secure.""" if not self._key or data is None: return data return b64encode(self._aes.encrypt(Padding.pad(data.encode(), 16))).decode()
def encrypt(msg, encrypt_key, hash_key): """ Encrypt and hash a message. Args: param msg: Bytes to encrypt param encrypt_key: Base64 encoded encryption key param hash_key: Base64 encoded hash key Returns: Base 64 encoded message """ encrypt_key = base64.b64decode(encrypt_key) hash_key = base64.b64decode(hash_key) padded_msg = Padding.pad(msg, BLOCK_SIZE, style="pkcs7") cipher = AES.new(encrypt_key, AES.MODE_CBC) encrypted_msg = cipher.encrypt(padded_msg) msg_hash = hmac.new(hash_key, cipher.iv + encrypted_msg, digestmod=hashlib.sha256).digest() return base64.b64encode(cipher.iv + encrypted_msg + msg_hash)
def getDES3(self, key, data, mode=DES3.MODE_ECB, block_size=8, style='pkcs7'): """ DES3加密 :param key: 秘钥key :param data: 未加密数据 :param mode: 加密模式 :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>` :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>` :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>` :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>` :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>` :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>` :var MODE_EAX: :ref:`EAX Mode <eax_mode>` :param block_size: 填充block大小:默认为8 :param style: 填充算法:‘pkcs7’(default),‘iso7816’or‘x923’ :return: 加密结果 byte string """ data = Padding.pad(data.encode('utf-8'), block_size=block_size, style=style) cipher = DES3.new(key.encode('utf-8'), mode=mode) return cipher.encrypt(data)
def secure_payload(self, msg_key, mac_key, msg): if (type(msg) != bytes): msg = msg.encode('utf-8') self.sqn_number += 1 payload_length = len(msg) padding_length = AES.block_size - payload_length % AES.block_size mac_length = 32 # SHA256 hash value is 32 bytes long msg_length = 27 + AES.block_size + payload_length + padding_length + mac_length # create header header_version = b'\x01\x01' # protocol version 1.1 header_type = self.client_addr.encode('utf-8') # message type 1 header_length = msg_length.to_bytes( 20, byteorder='big') # message length (encoded on 2 bytes) header_sqn = self.sqn_number.to_bytes( 4, byteorder='big' ) # next message sequence number (encoded on 4 bytes) header = header_version + header_type + header_length + header_sqn # pad the payload and encrypt the padded payload with AES in CBC mode using a random iv iv = get_random_bytes(AES.block_size) ENC = AES.new(msg_key, AES.MODE_CBC, iv) padded_payload = Padding.pad(msg, AES.block_size, style='iso7816') encrypted_payload = ENC.encrypt(padded_payload) # compute the mac on the header, iv, and encrypted payload MAC = HMAC.new(mac_key, digestmod=SHA256) MAC.update(header + iv + encrypted_payload) mac = MAC.digest() return header + iv + encrypted_payload + mac
def _encrypt_request_data(self, data, second_key): key = b'B@41Ner2' + second_key decryptor = AES.new(key, AES.MODE_ECB) data = data.encode('utf-8') data = Padding.pad(data, 16) enc = decryptor.encrypt(data) return base64.standard_b64encode(enc)
def encrypt(file, key_receiver): """ FUNCION: encrypt(file, key_receiver) ARGS_IN: file - nombre del fichero a encriptar key_receiver - clave publica del receptor DESCRIPCION: cifra un fichero dado por el metodo basado en RSA establecido ARGS_OUT: contenido cifrado (clave, iv, info cifrada - util en enc_sign) """ status = 'OK' # Creacion clave simetrica (de sesion) y vector de inicializacion key_simetric = get_random_bytes(AES_KEY_LEN) init_vector = get_random_bytes(IV_LEN) # Cifrado mensaje with open(file, 'r') as f: cipher_aes = AES.new(key_simetric, AES.MODE_CBC, init_vector) content = Padding.pad(f.read(), 16) ciphertext = cipher_aes.encrypt(content) # Cifrado clave de sesion key = RSA.importKey(key_receiver) cipher_rsa = PKCS1_OAEP.new(key) key_enc = cipher_rsa.encrypt(key_simetric) # Generacion fichero de salida f_name = 'enc_' + file with open(f_name, 'wb') as file_out: file_out.write(key_enc) file_out.write(init_vector) file_out.write(ciphertext) print 'Encriptando', file, '...', status return key_enc + init_vector + ciphertext
def ecb_enc(key, plaintext, ciphertext): #define Encryption function from Crypto import Random from Crypto.Cipher import AES from Crypto.Util import Padding f1 = open(key, 'r') #Opening the key.txt file in read mode sk_hex = f1.read() f1.close() #Closing the key.txt file sk = int(sk_hex, 16).to_bytes(32, byteorder='big') #sk = (f1.read()).strip('\n') #Reading the Secret Key f2 = open(plaintext, 'r') #Opening the plaintext.txt file in read mode message = (f2.readline()).strip('\n') #Reading the PlainText/Message f2.close() #Closing the plaintext.txt file obj = AES.new(sk, AES.MODE_ECB) padded_message = Padding.pad(str.encode(message), 16, 'pkcs7') #print(len((padded_message))) cipher = obj.encrypt(padded_message) cipher_hex = hex(int.from_bytes(cipher, byteorder='big', signed=False)) f4 = open(ciphertext, 'w') #Opening the ciphertext.txt file in write mode f4.write(cipher_hex) #Writing the CipherText f4.close() #Closing the ciphertext.txt file print(cipher) print(cipher_hex) #Printing the CipherText to command prompt
def encrypt(self, raw): iv = Random.get_random_bytes(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) # print("padd ", len(raw), raw, type(raw)) data = Padding.pad(raw.encode('utf-8'), AES.block_size, 'pkcs7') # print("padded", len(data), data, type(data)) return base64.b64encode(iv + cipher.encrypt(data))
def compose_ISO_msgs(self, shared_secret): # generate timestamp dd/mm/YY H:M:S now = datetime.datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") iso_msgs = {} # compose and send PubEnckpi+(A|K|T_Pk|Sigkpk-(B|K|T_Pk)) for each participant for recipient_addr in self.address_space: sig_payload = str.encode( recipient_addr) + shared_secret + str.encode(dt_string) signature = self.sig_manager.sign(sig_payload) # payload = A|K|T_Pk|Sigkpk-(B|K|T_Pk payload = str.encode( self.leader_addr) + shared_secret + str.encode(dt_string + signature) payload = Padding.pad(payload, AES.block_size) iso_msgs[recipient_addr] = self.hybrid_encrypt( recipient_addr, payload) print('Composed ISO11770 messages for each participant') return iso_msgs
def cbc_encrypt(key, password): if len(key) != 16: print('Error: Key must be 16 bytes') sys.exit(2) if len(password) == 0: print('Error: Password is missing.') sys.exit(2) # generate a random IV and encrypt it in ECB mode iv = Random.get_random_bytes(AES.block_size) cipher_ECB = AES.new(key, AES.MODE_ECB) enc_iv = cipher_ECB.encrypt(iv) # create an AES-CBC cipher object cipher_CBC = AES.new(key, AES.MODE_CBC, iv) # add padding padded_password = Padding.pad(password.encode('utf-8'), AES.block_size) # encrypt the plaintext encrypted_password = cipher_CBC.encrypt(padded_password) encrypted = enc_iv + encrypted_password return encrypted
def encode(plaintext_string, key, salt): """ AES256 encrypts a string, using provided key & 128bit salt The first 128bits of the returned ciphertext is an exact copy of the provided salt (to facilitate decryption). To store salt separately from the actual ciphertext, simply split off the first 128bits. Keyword Parameter: plaintext_string -- String to be enciphered. key -- Bytes, representing an 256bit AES private key. salt -- Bytes, representing a randomly generated (one-time-use), 128bit long AES Initialization Vector which will be used to salt the resulting ciphertext. >>> key = (b'\\x02\\xd2d\\xfb\\x84Q\\xed?\\x92\\xda\\xcd\\x9a/)' ... b'\\x15\\xdc\\xb5~\\\\\\x03\\xeby\\xa7\\xfb&#\\xb8' ... b'\\xd1y+a\\x86') >>> s = b'\\x94\\x99$y\\x83B\\x85N\\x94E\\x01L\\xe5\\xba\\xea\\xdf' >>> encode("Hello, World!", key, s) b'\\x94\\x99$y\\x83B\\x85N\\x94E\\x01L\\xe5\\xba\\xea\\xdf\\t\\xbc\\x84\\xf8L\\xd5adz\\x1bl\\x9f\\x9c\\x1db\\xb1' """ assert len(key) >= 256 / 8, "Private key must be 256bit, minimum" assert len(salt) == 128 / 8, "Expected (exactly) 128bit long salt" #per dlitz.net/software/pycrypto/api/current/Crypto.Cipher.AES-module.html aes256_cbc = AES.new(key, AES.MODE_CBC, IV=salt) # PKCS#7 CMS pad the input(AES requires input length as multiple of 16 bit) try: plaintext_bytes = plaintext_string.encode('utf-8') except AttributeError: plaintext_bytes = plaintext_string #Seems like it's already bytes padded_plaintext = Padding.pad(plaintext_bytes, 16, style='pkcs7') ciphertext = aes256_cbc.encrypt(padded_plaintext) # store our known-length iv for reuse,by simply prepending to ciphertext return salt + ciphertext #(safe to do) salt just stops rainbow table
def _encrypt(self, plaintext: bytes, iv: bytes, seq: int) -> bytes: cipher = AES.new(self.encrypt_key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(Padding.pad(plaintext, AES.block_size)) signature = self._sha256( self.hmac_key + seq.to_bytes(4, "big", signed=True) + ciphertext ) return signature + ciphertext
def encryptionAES(self, data, nonce): password = "******" key = hasher.sha256(password.encode('utf-8')).digest() data = Padding.pad(data.encode('utf-8'), 16) encryptor = AES.new(key, AES.MODE_CBC, IV=nonce) ciphertext = encryptor.encrypt(data) return ciphertext
def stream_transfer(file_path, chunk_size, connection): '''Send file using stream protocol. Stream transfer sends chunks of size X over connection. The first byte of X is a 1 or a 0, depending of if the chunk is the last in the stream, or not. The data is then end-padded to 16 bytes.''' #try: aes_key = get_key(connection) with open(file_path, mode='rb') as opened_file: filesize = os.stat(file_path).st_size while True: message = opened_file.read(chunk_size) if len(message) == 0: message = b'0' #if chunk_size <= 256 message = Padding.pad(message, 16) aes_cipher = AES.new(aes_key, AES.MODE_GCM) ciphertext, tag = aes_cipher.encrypt_and_digest(message) encrypted_message = aes_cipher.nonce + tag + ciphertext #for chunk in range(round(chunk_size/16)): # print('chunk', chunk) # to_encrypt = message[chunk * 16: (chunk_size + 1) * 16] # if chunk == 0: # digest = aes_cipher.digest() # print(len(digest)) # encrypted_message += digest # encrypted_message += aes_cipher.encrypt(to_encrypt) # else: # encrypted_message += aes_cipher.encrypt(to_encrypt) connection.send(encrypted_message) if opened_file.read(1): opened_file.seek(-1, 1) else: break return 'Transfer succeded from this end.'
def enkripcija(self, ulaz): ulaz = Padding.pad(ulaz, self.velicina_bloka) # popuni blok izlaz = '' for i in range(len(ulaz) // self.velicina_bloka): # posebno svaki blok izlaz += self.x.encrypt(ulaz[i * self.velicina_bloka:(i + 1) * self.velicina_bloka]) return izlaz
def encrypt(key, iv, data): try: cryptor = AES.new(key, AES.MODE_CBC, iv) new = cryptor.encrypt(Padding.pad(data, 16)) return new except Exception as e: return print(f'AESCBC.encrypt : {str(e)}')
def protect_firmware(infile, outfile, version, message): """ Arguments are: {infile} contains the firmware to be protected. {outfile} is where the encrypted firmware blob is written. {version} is the version of the firmware -- a positive integer value, or 0 to debug the firmware. {message} is the release message, which gets appended to the firmware and encrypted with it. firmware = firmware + message + "\0" Takes keys generated by the {bl_build} tool from "secret_build_output.txt". The {aes_key} is used to encrypt the firmware {fw}, and the {rsa_key} is used to sign the hash of a copy of the metadata, IV, and encrypted firmware. The plaintext and encrypted firmware will be referred to as "f" and "F" respectively. The overall structure of the firmware blob is such: metadata = version | size(f) | size(F) signed(hash(metadata | IV | F)) | metadata | IV | F Returns: 0 Outputs: {outfile} """ with open(infile, 'rb') as f: # reads firmware fw = f.read() print(fw) metadata = struct.pack( "<HH", version, len(fw) ) # packs initial metadata: version, length of unencrypted firmware fw = fw + message.encode( ) + b'\00' # appends release message to end of firmware with open("secret_build_output.txt", 'rb') as sec_output: aes_key = sec_output.read(16) # get symmetric key rsa_key = RSA.import_key(sec_output.read()) # get private key cipher = AES.new(aes_key, AES.MODE_CBC) # creates AES object encrypted_fw = cipher.encrypt(Padding.pad( fw, AES.block_size)) # encrypts firmware metadata += struct.pack( "<H", len(encrypted_fw)) # adds the length of encrypted firmware to metadata hashed_fw = SHA256.new( data=metadata + cipher.iv + encrypted_fw) # hashes the metadata, IV, and encrypted firmware signature = pkcs1_15.new(rsa_key).sign( hashed_fw ) # signs the hashed metadata, IV, and firmware using the private key fw_blob = signature + metadata + cipher.iv + encrypted_fw # creates blob to be sent to bootloader with open(outfile, "w+b") as out: # writes firmware blob to outfile out.write(fw_blob) return 0
def EncryptStringForNCX(self, s: str): cipher = AES.new(b'libcckeylibcckey', AES.MODE_CBC, iv=b'libcciv libcciv ') padded_plaintext = Padding.pad(s.encode('ascii'), AES.block_size, stype='pkcs7') return cipher.encrypt(padded_plaintext).hex().upper()
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(message: bytes, key: bytes, iv: bytes) -> bytes: """ Encrypt the `message` with AES-CBC algorithm. **Note that the type of parameter `message` is `bytes`.** `key` is the key used in AES algorithm, it should be of length 16, 24, or 32 bytes. `iv` should be of length 16 bytes. """ cipher = AES.new(key, AES.MODE_CBC, iv=iv) return cipher.encrypt(Padding.pad(message, 16))
def length_handler(data="", length=0): if len(data) < length: return Padding.pad(data.encode(), length) if len(data) > length: return data[0:15].encode() return data.encode()
def encrypt_message(message, date): byte_key = Encryption.get_key(date).encode() w = DES.new(byte_key, DES.MODE_CBC, byte_key) message = Padding.pad(message.encode(), 8, 'pkcs7') message = w.encrypt(message) message = base64.b64encode(message).decode().replace("+", "-") return message
def encrypt(self, plainText, key): aesCipher = AES.new(key, AES.MODE_CBC) byteText = Padding.pad(plainText.encode(), 16) cipherText = aesCipher.encrypt(byteText) #print(cipherText) cipherPacket = (aesCipher.iv + cipherText) return cipherPacket
def getEncryptText(message, key): messageEncode = bytes(message, encoding='utf-8') keyEncode = bytes(key, encoding="utf8") iv = '0102030405060708' ivEncode = bytes(iv, encoding="utf8") encryptor = AES.new(keyEncode, AES.MODE_CBC, ivEncode) text = encryptor.encrypt(Padding.pad(messageEncode, 16)) return base64.b64encode(text).decode("utf-8")
def encrypt(data: bytes, key: bytes) -> bytes: # pad data data = Padding.pad(data, 16) # new encryptor encryptor = AES.new(key, AES.MODE_CBC) # return IV + cipher return encryptor.iv + encryptor.encrypt(data)
def encrypt(key, **kwargs): payload = kwargs.get('FRMPayload').encode() pld_len = len(payload) // 2 payload = Padding.pad(payload, 16) k = math.ceil(pld_len / 16) cryptor = AES.new(key, AES.MODE_ECB) S = b'' for i in range(1, k + 1): kwargs['i'] = '{:0>2x}'.format(i) _A_each = DeviceOp._A(**kwargs) Ai = bytearray.fromhex(_A_each) Si = cryptor.encrypt(Ai) S += Si return b''.join(DeviceOp.bytes_xor(S, payload))[:pld_len * 2 + 1]