def doshit(): IV_LENGTH = 16 HMAC_KEY_LENGTH = 32 AES_KEY_LENGTH = 16 HMACKey = mycrypto.strong_random(HMAC_KEY_LENGTH) AESKey = mycrypto.strong_random(AES_KEY_LENGTH) IV = mycrypto.strong_random(IV_LENGTH) state = mycrypto.strong_random(112) aes = AES.new(AESKey, mode=AES.MODE_CBC, IV=IV) encrypted = mycrypto.strong_random(80) cryptedState = aes.encrypt(state) # Authenticate ticket name, IV and the encrypted state. hmac = HMAC.new(HMACKey, IV + \ cryptedState, digestmod=SHA256).digest() ticket = IV + cryptedState + hmac hmac = HMAC.new(HMACKey, ticket, digestmod=SHA256).digest() # Decrypt ticket to obtain state. aes = AES.new(AESKey, mode=AES.MODE_CBC, IV=ticket[0:16]) plainTicket = aes.decrypt(ticket)
def encrypt(self, data): if self.initialized == 0 and self.is_server == False: taddr = self.proto.factory.tun.addr taddr_hash = SHA384.new(taddr).digest() iv = Random.new().read(AES.block_size) salt = Random.new().read(SALT_LEN) passwd = self.proto.factory.passwd self.key = PBKDF2(passwd, salt, dkLen=AES_KEYLEN*2, count=PBKDF2_ITERATIONS) self.aes_e = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv) self.aes_d = AES.new(self.key[AES_KEYLEN:], AES.MODE_CFB, iv) data = iv+self.aes_e.encrypt(data) tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN] data = taddr_hash+salt+data+tag self.initialized = 1 else: data = self.aes_e.encrypt(data) tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN] data = data+tag return data
def decrypt(enc_message, key): h = HMAC.new(b'Key generation') h.update(bytes(key + ' this is a salt', 'ascii')) aes_key = h.digest() # Get the IV from the message iv = enc_message[0:16] cipher = AES.new(aes_key, AES.MODE_CBC, iv) decr_message = cipher.decrypt(enc_message[16:]) mac = decr_message[-16:] plaintext = decr_message[:-16] # Compute the MAC h = HMAC.new(aes_key) h.update(plaintext) computed_mac = h.digest() # If the computed MAC equals the ciphertext MAC, return the plaintext if computed_mac == mac: return plaintext # Simulates the timing attack # return 1 if the two MACs differ but share the same first byte # return 2 if the two MACs differ but share the same first two bytes if computed_mac[0] == mac[0]: return 2 if computed_mac[1] == mac[1] else 1 return 0
def runTest(self): key = b"0" * 16 data = b"\x00\x01\x02" def get_mv_ro(data): return memoryview(data) def get_mv_rw(data): return memoryview(bytearray(data)) for get_mv in (get_mv_ro, get_mv_rw): # Data and key can be a memoryview (during initialization) key_mv = get_mv(key) data_mv = get_mv(data) h1 = HMAC.new(key, data) h2 = HMAC.new(key_mv, data_mv) if not data_mv.readonly: key_mv[:1] = b'\xFF' data_mv[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest()) # Data can be a memoryview (during operation) data_mv = get_mv(data) h1 = HMAC.new(key) h2 = HMAC.new(key) h1.update(data) h2.update(data_mv) if not data_mv.readonly: data_mv[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest())
def _get_bytes(self, digest, key, label, random, num_bytes): bytes_ = "" block = HMAC.new(key=key, msg="%s%s" % (label, random), digestmod=digest).digest() while len(bytes_) < num_bytes: bytes_ += HMAC.new(key=key, msg="%s%s%s" % (block, label, random), digestmod=digest).digest() block = HMAC.new(key=key, msg=block, digestmod=digest).digest() return bytes_[:num_bytes]
def __init_crypto(self, pms, client_random, server_random, explicit_iv): self.master_secret = self.prf.get_bytes(pms, TLSPRF.TLS_MD_MASTER_SECRET_CONST, client_random + server_random, num_bytes=48) key_block = self.prf.get_bytes(self.master_secret, TLSPRF.TLS_MD_KEY_EXPANSION_CONST, server_random + client_random, num_bytes=2*(self.mac_key_length + self.cipher_key_length + self.iv_length) ) self.__init_key_material(key_block, explicit_iv) self.cipher_mode = self.negotiated_crypto_param["cipher"]["mode"] self.cipher_type = self.negotiated_crypto_param["cipher"]["type"] self.hash_type = self.negotiated_crypto_param["hash"]["type"] # Block ciphers if self.cipher_mode is not None: self.__client_enc_cipher = self.cipher_type.new(self.client_write_key, mode=self.cipher_mode, IV=self.client_write_IV) self.__client_dec_cipher = self.cipher_type.new(self.client_write_key, mode=self.cipher_mode, IV=self.client_write_IV) self.__server_enc_cipher = self.cipher_type.new(self.server_write_key, mode=self.cipher_mode, IV=self.server_write_IV) self.__server_dec_cipher = self.cipher_type.new(self.server_write_key, mode=self.cipher_mode, IV=self.server_write_IV) # Stream ciphers else: self.__client_enc_cipher = self.cipher_type.new(self.client_write_key) self.__client_dec_cipher = self.cipher_type.new(self.client_write_key) self.__server_enc_cipher = self.cipher_type.new(self.server_write_key) self.__server_dec_cipher = self.cipher_type.new(self.server_write_key) self.__client_hmac = HMAC.new(self.client_write_MAC_key, digestmod=self.hash_type) self.__server_hmac = HMAC.new(self.server_write_MAC_key, digestmod=self.hash_type)
def encrypt(cls, key, keyusage, plaintext, confounder): if confounder is None: confounder = get_random_bytes(8) ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest() cksum = HMAC.new(ki, confounder + plaintext, MD5).digest() ke = HMAC.new(ki, cksum, MD5).digest() return cksum + ARC4.new(ke).encrypt(confounder + plaintext)
def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'): GSS_GETMIC_HEADER = '\x60\x23\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02' token = self.MIC() # Let's pad the data pad = (8 - (len(data) % 8)) & 0x7 padStr = chr(pad) * pad data = data + padStr token['SGN_ALG'] = GSS_HMAC if direction == 'init': token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\x00'*4 else: token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\xff'*4 Ksign = HMAC.new(sessionKey.contents, 'signaturekey\0', MD5).digest() Sgn_Cksum = MD5.new( struct.pack('<L',15) + str(token)[:8] + data).digest() Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest() token['SGN_CKSUM'] = Sgn_Cksum[:8] Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest() Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest() token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ']) finalData = GSS_GETMIC_HEADER + token.getData() return finalData
def _derive_key(self, key, magic): hash1 = HMAC.new(key, magic, SHA).digest() hash2 = HMAC.new(key, hash1 + magic, SHA).digest() hash3 = HMAC.new(key, hash1, SHA).digest() hash4 = HMAC.new(key, hash3 + magic, SHA).digest() return hash2 + hash4[0:4]
def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction="init"): GSS_GETMIC_HEADER = "\x60\x23\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" token = self.MIC() # Let's pad the data pad = (4 - (len(data) % 4)) & 0x3 padStr = chr(pad) * pad data = data + padStr token["SGN_ALG"] = GSS_HMAC if direction == "init": token["SND_SEQ"] = struct.pack(">L", sequenceNumber) + "\x00" * 4 else: token["SND_SEQ"] = struct.pack(">L", sequenceNumber) + "\xff" * 4 Ksign = HMAC.new(sessionKey.contents, "signaturekey\0", MD5).digest() Sgn_Cksum = MD5.new(struct.pack("<L", 15) + str(token)[:8] + data).digest() Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest() token["SGN_CKSUM"] = Sgn_Cksum[:8] Kseq = HMAC.new(sessionKey.contents, struct.pack("<L", 0), MD5).digest() Kseq = HMAC.new(Kseq, token["SGN_CKSUM"], MD5).digest() token["SND_SEQ"] = ARC4.new(Kseq).encrypt(token["SND_SEQ"]) finalData = GSS_GETMIC_HEADER + token.getData() return finalData
def runTest(self): key = b"0" * 16 data = b"\x00\x01\x02" # Data and key can be a bytearray (during initialization) key_ba = bytearray(key) data_ba = bytearray(data) h1 = HMAC.new(key, data) h2 = HMAC.new(key_ba, data_ba) key_ba[:1] = b'\xFF' data_ba[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest()) # Data can be a bytearray (during operation) key_ba = bytearray(key) data_ba = bytearray(data) h1 = HMAC.new(key) h2 = HMAC.new(key) h1.update(data) h2.update(data_ba) data_ba[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest())
def main(): assert(normal() == True) N = 0xEEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3 g = 2 k = 3 salt = 0 word_dict = [b'password', b'12345', b'abcdefg', b'test123', b'poc', b'as123434faw', b'dog', b'cat', b'atleast15', b'orsomethinglikethat', b'kfjasda', b'badpw', b'shadow!!!!'] P = choice(word_dict) I = b'username' # the lazy way! S = {} C = {} S["salt"] = salt C["a"] = randint(1, 0xFFFFFFFF) C["I"] = I S["I"] = C["I"] C["A"] = fast_pow(g, C["a"], N) S["A"] = C["A"] S["b"] = 2 S["B"] = fast_pow(g, S["b"], N) S["u"] = 1 C["salt"] = S["salt"] C["B"] = S["B"] C["u"] = S["u"] hasher = SHA256.new() hasher.update(bytes(format(salt, 'x'), 'ascii') + P) C["x"] = hasher.hexdigest() C["S"] = fast_pow(C["B"], (C["a"] + C["u"] * int(C["x"], 16)), N) hasher = SHA256.new() hasher.update(bytes(format(C["S"], 'x'), 'ascii')) C["K"] = hasher.hexdigest() hasher = HMAC.new(bytes(C["K"], 'ascii'), bytes(format(C["salt"], 'x'), 'ascii'), SHA256) C["hmac"] = hasher.hexdigest() for word in word_dict: hasher = SHA256.new() hasher.update(bytes(format(salt, 'x'), 'ascii') + word) S["x"] = hasher.hexdigest() S["v"] = fast_pow(g, int(S["x"], 16), N) S["S"] = fast_pow(S["A"] * fast_pow(S["v"], S["u"], N), S["b"], N) hasher = SHA256.new() hasher.update(bytes(format(S["S"], 'x'), 'ascii')) S["K"] = hasher.hexdigest() hasher = HMAC.new(bytes(S["K"], 'ascii'), bytes(format(S["salt"], 'x'), 'ascii'), SHA256) S["hmac"] = hasher.hexdigest() #S->C Send "OK" if HMAC-SHA256(K, salt) validates if S["hmac"] == C["hmac"]: print('win') break
def encrypt(etype, key, msg_type, data): if etype != RC4_HMAC: raise NotImplementedError('Only RC4-HMAC supported!') k1 = HMAC.new(key, pack('<I', msg_type)).digest() data = random_bytes(8) + data chksum = HMAC.new(k1, data).digest() k3 = HMAC.new(k1, chksum).digest() return chksum + ARC4.new(k3).encrypt(data)
def _got_rakp2(self,data): if not (self.sessioncontext in ('EXPECTINGRAKP2','EXPECTINGRAKP4')): return -9 #if we are not expecting rakp2, ignore. In a retry #scenario, replying from stale RAKP2 after sending #RAKP3 seems to be best if data[0] != self.rmcptag: #ignore mismatched tags for retry logic return -9 if data[1] != 0: #if not successful, consider next move if data[1] == 2: #invalid sessionid 99% of the time means a retry #scenario invalidated an in-flight transaction return if data[1] in rmcp_codes: errstr=rmcp_codes[data[1]] else: errstr="Unrecognized RMCP code %d"%data[1] call_with_optional_args(self.onlogon, {'error': errstr+" in RAKP2"}, self.onlogonargs) return -9 localsid=unpack("<I",pack("4B",*data[4:8]))[0] if localsid != self.localsid: return -9 #discard mismatch in the session identifier self.remoterandombytes = pack("16B",*data[8:24]) self.remoteguid=pack("16B",*data[24:40]) userlen=len(self.userid) hmacdata=pack("<II",localsid,self.pendingsessionid)+\ self.randombytes+self.remoterandombytes+self.remoteguid+\ pack("2B",self.privlevel,userlen)+\ self.userid import binascii expectedhash = HMAC.new(self.password,hmacdata,SHA).digest() givenhash = pack("%dB"%len(data[40:]),*data[40:]) hash = binascii.hexlify(hmacdata) salt = binascii.hexlify(givenhash) print "%s@%s:$rakp$%s$%s" % (self.userid, self.bmc, binascii.hexlify(hmacdata), binascii.hexlify(givenhash)) if givenhash != expectedhash: self.sessioncontext = 'FAILED' self.logged = True # dirty hack self.nowait=False self._cleanup() return -9 self.nowait=False return 0 #We have now validated that the BMC and client agree on password, time #to store the keys self.sik=HMAC.new(self.kg, self.randombytes+self.remoterandombytes+ pack("2B",self.privlevel,userlen)+ self.userid,SHA).digest() self.k1=HMAC.new(self.sik,'\x01'*20,SHA).digest() self.k2=HMAC.new(self.sik,'\x02'*20,SHA).digest() self.aeskey=self.k2[0:16] self.sessioncontext="EXPECTINGRAKP4" self._send_rakp3()
def decrypt(etype, key, msg_type, encrypted): if etype != RC4_HMAC: raise NotImplementedError('Only RC4-HMAC supported!') chksum = encrypted[:16] data = encrypted[16:] k1 = HMAC.new(key, pack('<I', msg_type)).digest() k3 = HMAC.new(k1, chksum).digest() data = ARC4.new(k3).decrypt(data) if HMAC.new(k1, data).digest() != chksum: raise ValueError('Decryption failed! (checksum error)') return data[8:]
def _got_rakp2(self, data): if data[16] != self._rmcptag: # use rmcp tag to track and reject stale responses logging.warning("!rmcptag") return False if data[17] != 0: # response code if data[17] in (9, 0xd) and self._privlevel == 4: # Here the situation is likely that the peer didn't want # us to use Operator. Degrade to operator and try again self._initsession() self._privlevel = 3 return True if data[17] == 2: # invalid sessionid 99% of the time means a retry # scenario invalidated an in-flight transaction self._initsession() return True logging.warning('%s %s %s %s' % (self._host, self._userid, "err_rakp2", self.rmcp_codes.get(data[17], 'Unrecognized RMCP code %d' % data[17]))) # data[17] === 13 -> incorrect password self._relog() return False localsid = unpack('<I', pack('4B', *data[20:24]))[0] if self._localsid != localsid: return False self._remoterandombytes = pack('16B',*data[24:40]) self._remoteguid = pack('16B',*data[40:56]) userlen = len(self._userid) hmacdata = pack("<I4B", localsid, *self._pendingsessionid)+\ self._randombytes + self._remoterandombytes + self._remoteguid+\ pack('2B', self._privlevel, userlen) +\ self._userid expectedhash = HMAC.new(self._passwd, hmacdata, SHA).digest() givenhash = pack('%dB' % len(data[56:]),*data[56:]) if givenhash != expectedhash: logging.warning("%s %s" % (self._host, "Incorrect password provided")) self.disconnect() return False #We have now validated that the BMC and client agree on password, time #to store the keys self._sik = HMAC.new(self._kg, self._randombytes + self._remoterandombytes + pack('2B', self._privlevel, userlen)+ self._userid, SHA).digest() self._k1 = HMAC.new(self._sik, b'\x01'*20, SHA).digest() self._k2 = HMAC.new(self._sik, b'\x02'*20, SHA).digest() self._aeskey = self._k2[0:16] self._send = self._send_rakp3 return True
def runTest(self): key = b"\x90\x91\x92\x93" * 4 payload = b"\x00" * 100 for hashname, hashmod in self.hashmods.items(): if hashmod is None: continue self.description = "Test HMAC in combination with " + hashname one = HMAC.new(key, payload, hashmod).digest() two = HMAC.new(key, payload, hashmod.new()).digest() self.assertEqual(one, two)
def lmntchallengeresponse(self): responseKeyNT = self.ntowfv2() responseKeyLM = self.lmowfv2() ## LMv2 lmchallengeresp = HMAC.new(responseKeyLM, self.serverChallenge + self.clientChallenge).digest() + self.clientChallenge ## NTv2 timestamp = self.getNTTimestamp() temp = '\x01\x01'+'\x00'*6+pack('<Q',timestamp)+self.clientChallenge+'\x00'*4+self.targetInfo+'\x00'*4 ntproofstr = HMAC.new(responseKeyNT, self.serverChallenge + temp).digest() ntchallengeresp = ntproofstr + temp #sessionKey = HMAC.new(responseKeyNT, ntproofstr).digest() return (lmchallengeresp, ntchallengeresp)
def p_hash(self, secret, seed): a_i = seed # i=0 ''' 1) ##############i=0 hmac_hash(secret, seed+seed) + i=1 hmac_hash(secret, hmac_hash(secret, seed) +seed) + i=2 hmac_hash(secret, hmac_hash(secret, ''' #start at i=1 while True: a_i = HMAC.new(key=secret, msg=a_i, digestmod=self.algorithm).digest() # i=1 yield HMAC.new(key=secret, msg=a_i+seed, digestmod=self.algorithm).digest()
def decrypt( ticket, srvState ): """ Decrypts, verifies and returns the given `ticket'. The key material used to verify the ticket is contained in `srvState'. First, the HMAC over the ticket is verified. If it is valid, the ticket is decrypted. Finally, a `ProtocolState()' object containing the master key and the ticket's issue date is returned. If any of these steps fail, `None' is returned. """ assert (ticket is not None) and (len(ticket) == const.TICKET_LENGTH) assert (srvState.hmacKey is not None) and (srvState.aesKey is not None) log.debug("Attempting to decrypt and verify ticket.") checkKeys(srvState) # Verify the ticket's authenticity before decrypting. hmac = HMAC.new(srvState.hmacKey, ticket[0:80], digestmod=SHA256).digest() if util.isValidHMAC(hmac, ticket[80:const.TICKET_LENGTH], srvState.hmacKey): aesKey = srvState.aesKey else: if srvState.oldHmacKey is None: return None # Was the HMAC created using the rotated key material? oldHmac = HMAC.new(srvState.oldHmacKey, ticket[0:80], digestmod=SHA256).digest() if util.isValidHMAC(oldHmac, ticket[80:const.TICKET_LENGTH], srvState.oldHmacKey): aesKey = srvState.oldAesKey else: return None # Decrypt the ticket to extract the state information. aes = AES.new(aesKey, mode=AES.MODE_CBC, IV=ticket[0:const.TICKET_AES_CBC_IV_LENGTH]) plainTicket = aes.decrypt(ticket[const.TICKET_AES_CBC_IV_LENGTH:80]) issueDate = struct.unpack('I', plainTicket[0:4])[0] identifier = plainTicket[4:22] masterKey = plainTicket[22:54] if not (identifier == const.TICKET_IDENTIFIER): log.error("The ticket's HMAC is valid but the identifier is invalid. " "The ticket could be corrupt.") return None return ProtocolState(masterKey, issueDate=issueDate)
def _got_rakp2(self, data): if not (self.sessioncontext in ('EXPECTINGRAKP2', 'EXPECTINGRAKP4')): return -9 # if we are not expecting rakp2, ignore. In a retry # scenario, replying from stale RAKP2 after sending # RAKP3 seems to be best if data[0] != self.rmcptag: # ignore mismatched tags for retry logic return -9 if data[1] != 0: # if not successful, consider next move if data[1] == 2: # invalid sessionid 99% of the time means a retry # scenario invalidated an in-flight transaction return if data[1] in constants.rmcp_codes: errstr = constants.rmcp_codes[data[1]] else: errstr = "Unrecognized RMCP code %d" % data[1] call_with_optional_args(self.onlogon, {'error': errstr + " in RAKP2"}, self.onlogonargs) return -9 localsid = struct.unpack("<I", struct.pack("4B", *data[4:8]))[0] if localsid != self.localsid: return -9 # discard mismatch in the session identifier self.remoterandombytes = struct.pack("16B", *data[8:24]) self.remoteguid = struct.pack("16B", *data[24:40]) userlen = len(self.userid) hmacdata = struct.pack("<II", localsid, self.pendingsessionid) +\ self.randombytes + self.remoterandombytes + self.remoteguid +\ struct.pack("2B", self.privlevel, userlen) +\ self.userid expectedhash = HMAC.new(self.password, hmacdata, SHA).digest() givenhash = struct.pack("%dB" % len(data[40:]), *data[40:]) if givenhash != expectedhash: self.sessioncontext = "FAILED" call_with_optional_args(self.onlogon, {'error': "Incorrect password provided"}, self.onlogonargs) return -9 # We have now validated that the BMC and client agree on password, time # to store the keys self.sik = HMAC.new(self.kg, self.randombytes + self.remoterandombytes + struct.pack("2B", self.privlevel, userlen) + self.userid, SHA).digest() self.k1 = HMAC.new(self.sik, '\x01' * 20, SHA).digest() self.k2 = HMAC.new(self.sik, '\x02' * 20, SHA).digest() self.aeskey = self.k2[0:16] self.sessioncontext = "EXPECTINGRAKP4" self.lastpayload = None self._send_rakp3()
def _startEncryption(self): # check signature, decrypt self.enc fields = ( self.byteformat.pack(P_ACKNOWLEDGE_SERVICE), self.enc, self.eniv, self.biscuit, self.fingerprint, self.cookie ) if not self.keymanager.verify(''.join(fields), self.signature, self.hostkey): raise InvalidSignatureException('Server failed to sign message') # decrypt the server biscuit and secret key ensecret = self.keymanager.decrypt(self.enc) # generate cipher parameters for the server's packets desecret = self.prng.read(Z_SECRET_KEY_LENGTH) deiv = self.prng.read(self.cipherscheme.block_size) # start up the ciphers for enc/dec mode = self.cipherscheme.MODE_CBC self.encipher = self.cipherscheme.new(ensecret, mode, self.eniv) self.decipher = self.cipherscheme.new(desecret, mode, deiv) # sequence numbers self.enseqno = 0 self.deseqno = 0 # authenticity self.ehmac = HMAC.new(ensecret, digestmod=SHA256) self.dhmac = HMAC.new(desecret, digestmod=SHA256) # update with IV self.ehmac.update(self.eniv) self.dhmac.update(deiv) # send the encryption start packet fields = ( P_REQUEST_ENCRYPTION_START, self.keymanager.encrypt(desecret, self.hostkey), deiv ) packetformat = Struct('!B256s%ds' % self.cipherscheme.block_size) packet = packetformat.pack(*fields) # sign this message signature = self.keymanager.sign(packet + self.biscuit) # send it self.sock.send(packet + signature) # redirect function pointer self.parseBuffer = self._unpackPackets # enter interactive mode self.r_cwd = '' if not self.config.target: self.command()
def mbi_crypt(self, nonce): WINCRYPT_CRYPT_MODE_CBC = 1 WINCRYPT_CALC_3DES = 0x6603 WINCRYPT_CALC_SHA1 = 0x8004 # Read key and generate two derived keys key1 = base64.b64decode(self.proof_token) key2 = self._derive_key(key1, "WS-SecureConversationSESSION KEY HASH") key3 = self._derive_key(key1, "WS-SecureConversationSESSION KEY ENCRYPTION") # Create a HMAC-SHA-1 hash of nonce using key2 hash = HMAC.new(key2, nonce, SHA).digest() # # Encrypt nonce with DES3 using key3 # # IV (Initialization Vector): 8 bytes of random data iv = randpool.RandomPool().get_bytes(8) obj = DES3.new(key3, DES3.MODE_CBC, iv) # XXX: win32's Crypt API seems to pad the input with 0x08 bytes # to align on 72/36/18/9 boundary ciph = obj.encrypt(nonce + "\x08\x08\x08\x08\x08\x08\x08\x08") blob = struct.pack("<LLLLLLL", 28, WINCRYPT_CRYPT_MODE_CBC, WINCRYPT_CALC_3DES, WINCRYPT_CALC_SHA1, len(iv), len(hash), len(ciph)) blob += iv + hash + ciph return base64.b64encode(blob)
def decrypt_gen_aead_AES128CBC_HMACSHA256(key, n, iv, content): # Split the key into encryption and authentication halves assert( len(key) == 16 + SHA256.digest_size ) ke = key[-16:] ka = key[:-16] # Split the encrypted content and integrity check S = content[:-SHA256.digest_size] T = content[-SHA256.digest_size:] # Verify the MAC hmac = HMAC.new(ka, digestmod=SHA256) ln = struct.pack("!q", len(n)) la = struct.pack("!q", 0) hmac.update(n + S + ln + la) Tp = hmac.digest() if Tp != T: raise Exception("Integrity check failed") # Decrypt the contents cipher = AES.new(ke, AES.MODE_CBC, iv) pcontent = cipher.decrypt(S) # Trim the padding lp = struct.unpack("B", content[-1])[0] pcontent = pcontent[:-lp] return pcontent
def write_logfile(log_filename, auth_token, logfile_pt): # Compress the plaintext log file logfile_pt = zlib.compress(logfile_pt, 5) # Generate the encryption and hmac keys from the token encrypt_key, hmac_key = generate_keys(auth_token) # Set-up the counter for AES CTR-mode cipher ctr_iv = urandom(16) ctr = Counter.new(128, initial_value=long(ctr_iv.encode('hex'),16)) # AES is 128 bits (16 bytes) logfile_ct = ctr_iv.encode('hex') # Create the cipher object cipher = AES.new(encrypt_key.decode('hex'), AES.MODE_CTR, counter=ctr) # Encrypt the plain text log and add it to the logfile cipher text # which currently contains the IV for AES CTR mode logfile_ct = logfile_ct + cipher.encrypt(logfile_pt) # Use the 2nd half of the hashed token to sign the cipher text # version of the logfile using a MAC (message authentication code) hmac_obj = HMAC.new(hmac_key.decode('hex'), logfile_ct) mac = hmac_obj.hexdigest() # Add the mac to the encrypted log file logfile_ct = logfile_ct + mac # Write the signed and encrypted log file to disk. # The caller should handle an IO exception with open(log_filename, 'wb') as f: f.write(logfile_ct) return None
def encrypt_gen_aead_AES128CBC_HMACSHA256(key, n, iv, content): # Split the key into encryption and authentication halves assert( len(key) == 16 + SHA256.digest_size ) ke = key[-16:] ka = key[:-16] # Pad the content x = AES.block_size - (len(content) % AES.block_size) if x == 0: x = AES.block_size econtent = content + (struct.pack("B",x) * x) # Compute the encrypted body assert( len(iv) == AES.block_size ) cipher = AES.new(ke, AES.MODE_CBC, iv) S = cipher.encrypt(econtent) # Compute the authentication value hmac = HMAC.new(ka, digestmod=SHA256) ln = struct.pack("!q", len(n)) la = struct.pack("!q", 0) hmac.update(n + S + ln + la) T = hmac.digest() return S + T
def hmac(message, key): """ Returns the Hash Message Authentication Code for a given message, providing integrity and authenticity assurances. """ h = HMAC.new(to_bytes(key), to_bytes(message), digestmod=SHA256) return h.hexdigest()
def decrypt_hash(edata, nlkm, ch): hmac_md5 = HMAC.new(nlkm, ch) rc4key = hmac_md5.digest() rc4 = ARC4.new(rc4key) data = rc4.encrypt(edata) return data
def receiveMessage(self): if self.connection is None or self._role is None: return ("No connection exists.", -3) try: data = self.connection.recv(self.__buffer_size) if data is not None and len(data) > 0: if self.__decrypt_cipher is not None: authenticator, data = data[0:64], data[64:] #the first half of any post-handshake message will be a 64-byte hex string of the authenticator, then the rest is the message reauthentication_hasher = HMAC.new(self.__auth_recv_hmac, digestmod=SHA256.new()) reauthentication_hasher.update(data) reauthentication_hasher.update(str(self.__num_msg_recv)) reauthenticator = reauthentication_hasher.hexdigest() if not self.__constant_time_equality(authenticator, reauthenticator): return ("Authentication of message failed.", -4) self.__num_msg_recv += 1 data = self.__decrypt_cipher.decrypt(base64.b64decode(data)) if "\x02" in data: #the data was a list of message components, reconstruct the list as the return value #note that this should only happen during chat transport, when the decryption cipher is valid #\x02 bytes could appear during key exchange as well, which we do not want to alter, so this transform #only occurs when the encryption system is fully functioning and set up data = data.split("\x02") with open("x.txt", "w") as log: log.write(str(len(data)) + "\n") return (data, 0) else: return ("No connection.", -1) except Exception: return ("No data recieved.", -2)
def _aesDecrypt(bundle): ''' Decrypt Target Encrypted Bundle ''' # Get Decryption Keys # key_dict = _getKeyPair() aes_key = str(key_dict['aes_key']).rstrip('\n') hmac_key = str(key_dict['hmac_key']).rstrip('\n') # Get Cipher Text # with open(bundle, 'r') as fh_: cipher_text = fh_.read() # Decrypt Cipher Text # header = cipher_text[:32] data = cipher_text[32:] aes_tag = data[:AES.block_size] aes_body = data[AES.block_size:] aes = AES.new(aes_key, AES.MODE_CFB, aes_tag) plain_text = aes.decrypt(aes_body) # Compare HMAC for Data Integrity # hmac_tag = HMAC.new(hmac_key, data, SHA256).digest() hmac_check = 0 for char1, char2 in zip(aes_tag, hmac_tag): hmac_check != ord(char1) ^ ord(char2) # Decompress Vault # if hmac_check == 0: plain_text = json.loads(str(zlib.decompress(plain_text).decode('utf-8'))) return json.dumps(plain_text, sort_keys=True, indent=2, separators=(',', ':')) else: return 'Digest mismatch - vault integrity compromised!'
def hmac_sign(s, key, mod=SHA256): hmac = HMAC.new(key, digestmod=mod) hmac.update(s) return hmac.digest()
def PBKDF2(password, salt, dkLen=16, count=1000, prf=None, hmac_hash_module=None): """Derive one or more keys from a password (or passphrase). This function performs key derivation according to the PKCS#5 standard (v2.0). Args: password (string or byte string): The secret password to generate the key from. salt (string or byte string): A (byte) string to use for better protection from dictionary attacks. This value does not need to be kept secret, but it should be randomly chosen for each derivation. It is recommended to use at least 16 bytes. dkLen (integer): The cumulative length of the keys to produce. Due to a flaw in the PBKDF2 design, you should not request more bytes than the ``prf`` can output. For instance, ``dkLen`` should not exceed 20 bytes in combination with ``HMAC-SHA1``. count (integer): The number of iterations to carry out. The higher the value, the slower and the more secure the function becomes. You should find the maximum number of iterations that keeps the key derivation still acceptable on the slowest hardware you must support. Although the default value is 1000, **it is recommended to use at least 1000000 (1 million) iterations**. prf (callable): A pseudorandom function. It must be a function that returns a pseudorandom byte string from two parameters: a secret and a salt. The slower the algorithm, the more secure the derivation function. If not specified, **HMAC-SHA1** is used. hmac_hash_module (module): A module from ``Crypto.Hash`` implementing a Merkle-Damgard cryptographic hash, which PBKDF2 must use in combination with HMAC. This parameter is mutually exclusive with ``prf``. Return: A byte string of length ``dkLen`` that can be used as key material. If you want multiple keys, just break up this string into segments of the desired length. """ password = tobytes(password) salt = tobytes(salt) if prf and hmac_hash_module: raise ValueError("'prf' and 'hmac_hash_module' are mutually exlusive") if prf is None and hmac_hash_module is None: hmac_hash_module = SHA1 if prf or not hasattr(hmac_hash_module, "_pbkdf2_hmac_assist"): # Generic (and slow) implementation if prf is None: prf = lambda p, s: HMAC.new(p, s, hmac_hash_module).digest() def link(s): s[0], s[1] = s[1], prf(password, s[1]) return s[0] key = b'' i = 1 while len(key) < dkLen: s = [prf(password, salt + struct.pack(">I", i))] * 2 key += reduce(strxor, (link(s) for j in range(count))) i += 1 else: # Optimized implementation key = b'' i = 1 while len(key) < dkLen: base = HMAC.new(password, b"", hmac_hash_module) first_digest = base.copy().update(salt + struct.pack(">I", i)).digest() key += base._pbkdf2_hmac_assist(first_digest, count) i += 1 return key[:dkLen]
""" print('Original text:\n==========') print(text) print('==========') # first transform the text into packets blocks = [] size = 40 for i in range(0, len(text), size): blocks.append(text[i:i + size]) # now get MACs for all the text blocks. The key is obvious... print('Calculating MACs...') from Crypto.Hash import HMAC, SHA key = 'Jefferson' macs = [HMAC.new(key, block, digestmod=SHA).digest() for block in blocks] assert len(blocks) == len(macs) # put these into a form acceptable as input to the chaffing procedure source = [] m = list(zip(list(range(len(blocks))), blocks, macs)) print(m) for i, data, mac in m: source.append((i, data, mac)) # now chaff these print('Adding chaff...') c = Chaff(factor=0.5, blocksper=2) chaffed = c.chaff(source)
def __init__(self): self.salt_size = 8 # bytes self.tag_size = 8 # bytes self.mac_size = 8 # bytes; mac = message authentication code (MAC) self.prf = lambda p, s: HMAC.new(p, s, SHA256).digest()
def gen_signature(client_secret, access_secret, base_string): key = '&'.join([client_secret, access_secret]).encode('ascii') string_to_sign = base_string.encode('utf-8') hmac = HMAC.new(key, string_to_sign, SHA) return b64encode(hmac.digest()).decode()
def _hmac(self, key, data): return HMAC.new(key, data, self.HASH).digest()
def _pbkdf2_prf(p, s): hash_function = SHA256_pycrypto return HMAC_pycrypto.new(p, s, hash_function).digest()
def _pbkdf2(password, salt, n_bytes, count): # the form of the prf below is taken from the code for PBKDF2 return PBKDF2(password, salt, dkLen=n_bytes, count=count, prf=lambda p,s: HMAC.new(p,s,HASH).digest())
def _hmac(key, data): return HMAC.new(key, data, HASH).digest()
def GSS_Wrap(self, sessionKey, data, sequenceNumber, direction = 'init', encrypt=True, authData=None): # Damn inacurate RFC, useful info from here # https://social.msdn.microsoft.com/Forums/en-US/fb98e8f4-e697-4652-bcb7-604e027e14cc/gsswrap-token-size-kerberos-and-rc4hmac?forum=os_windowsprotocols # and here # http://www.rfc-editor.org/errata_search.php?rfc=4757 GSS_WRAP_HEADER = '\x60\x2b\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02' token = self.WRAP() # Let's pad the data pad = (8 - (len(data) % 8)) & 0x7 padStr = chr(pad) * pad data = data + padStr token['SGN_ALG'] = GSS_HMAC token['SEAL_ALG'] = GSS_RC4 if direction == 'init': token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\x00'*4 else: token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\xff'*4 # Random confounder :) token['Confounder'] = '12345678' Ksign = HMAC.new(sessionKey.contents, 'signaturekey\0', MD5).digest() Sgn_Cksum = MD5.new(struct.pack('<L',13) + str(token)[:8] + token['Confounder'] + data).digest() Klocal = '' for n in sessionKey.contents: Klocal += chr(ord(n) ^ 0xF0) Kcrypt = HMAC.new(Klocal,struct.pack('<L',0), MD5).digest() Kcrypt = HMAC.new(Kcrypt,struct.pack('>L', sequenceNumber), MD5).digest() Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest() token['SGN_CKSUM'] = Sgn_Cksum[:8] Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest() Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest() token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ']) if authData is not None: from impacket.dcerpc.v5.rpcrt import SEC_TRAILER wrap = self.WRAP(authData[len(SEC_TRAILER()) + len(GSS_WRAP_HEADER):]) snd_seq = wrap['SND_SEQ'] Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest() Kseq = HMAC.new(Kseq, wrap['SGN_CKSUM'], MD5).digest() snd_seq = ARC4.new(Kseq).encrypt(wrap['SND_SEQ']) Kcrypt = HMAC.new(Klocal,struct.pack('<L',0), MD5).digest() Kcrypt = HMAC.new(Kcrypt,snd_seq[:4], MD5).digest() rc4 = ARC4.new(Kcrypt) cipherText = rc4.decrypt(token['Confounder'] + data)[8:] elif encrypt is True: rc4 = ARC4.new(Kcrypt) token['Confounder'] = rc4.encrypt(token['Confounder']) cipherText = rc4.encrypt(data) else: cipherText = data finalData = GSS_WRAP_HEADER + token.getData() return cipherText, finalData
def XeCryptHmacSha(key: Union[bytes, bytearray], *args: Union[bytes, bytearray]) -> bytes: hasher = HMAC.new(key, digestmod=SHA1) [hasher.update(x) for x in args] return hasher.digest()
from Crypto.Hash import HMAC secret = 'Swordfish' h=HMAC.new(secret) h.update("Hello") print(h.hexdigest())
def _hmac(key, msg): h = HMAC.new(key, b"", digestmod=SHA256) h.update(msg) return h.digest()
import base64 import json from Crypto.Hash import HMAC, SHA512 from Crypto.Random import get_random_bytes msg = b'This is the message to use to compute the HMAC' key = get_random_bytes(32) hmac_gen = HMAC.new(key, digestmod=SHA512) hmac_gen.update(msg[:10]) hmac_gen.update(msg[10:]) mac = hmac_gen.hexdigest() #store message and MAC into a JSON data structure json_dict = {"message": msg.decode('utf-8'), "MAC":mac} json_object = json.dumps(json_dict) print(json_object) # ASSUMPTION: we have securely exchanged the secret key b64 = json.loads(json_object) hmac_ver = HMAC.new(key, digestmod=SHA512) hmac_ver.update(b64["message"].encode('utf-8')) try: hmac_ver.hexverify(b64["MAC"]) print("The message '%s' is authentic" % msg) except ValueError: print("The message or the key is wrong")
from Crypto.Hash import SHA512, HMAC documento = 'ejercicio1ab.txt' leedocumento = open(documento,"r") texto = leedocumento.read() leedocumento.close() clave = b'S3cr3tK3y' codigohash = HMAC.new(clave,digestmod=SHA512) codigohash.update(texto.encode("UTF-8")) print("El HMAC-SHA512 de dicho fichero es:") print(codigohash.hexdigest()) firma = codigohash.digest() try: codigohash.verify(firma) print("La firma es válida") except (ValueError,TypeError): print("La firma no es válida")
def pw_hash_four(password, key): hash = HMAC.new(key, password, SHA256) return hash.digest()
def __key_hash_genarator(self): return PBKDF2(self.key, self.salt, prf=lambda p, s: HMAC.new(p, s, SHA256).digest())
def pw_hash_three(password): key = "".encode() hash = HMAC.new(key, password, SHA256) return hash.digest()
def _pbkdf2(self, password, salt, n_bytes, count): return PBKDF2(password, salt, dkLen=n_bytes, count=count, prf=lambda p, s: HMAC.new(p, s, self.HASH).digest())
def MacEngine(self, ciphertext): hm = HMAC.new(self.MKs, digestmod=SHA) hm.update(ciphertext) return hm.digest()
from Crypto.Hash import HMAC, SHA256 from Crypto.Random import get_random_bytes import json msg = b'This is the message to use to computer a MAC' key = get_random_bytes(32) hmac_generator = HMAC.new(key, digestmod=SHA256) hmac_generator.update(msg[:10]) hmac_generator.update(msg[10:]) mac = hmac_generator.hexdigest() print(mac) # JSON Dictionary json_dict = {'message': msg.decode('utf-8'), 'MAC': mac} # JSON Object json_obj = json.dumps(json_dict) print(json_obj) # Receiver # key shared securely # public channel: json object jo = json.loads(json_obj) hmac_verifier = HMAC.new(key, digestmod=SHA256) hmac_verifier.update(jo["message"].encode('utf-8')) try: hmac_verifier.hexverify(jo["MAC"]) print("The message is authentic\n")
def _get_reseted_hmac(self): # http://crypto.stackexchange.com/questions/8272/injecting-salt-into-pycrypto-kdf-useful return cHMAC.new(self.secret, msg=self.salt, digestmod=self.digestmod)
def signature_HS256(key: bytes, data: bytes) -> bytes: hmac = HMAC.new(key, msg=data, digestmod=SHA256) return hmac.digest()
def VerificationEngine(self, ciphertext): hm = HMAC.new(self.MKc, digestmod=SHA) hm.update(ciphertext) return hm.digest()
def pw_hash_two(password, salt=get_random_bytes(10)): hash = HMAC.new(password, salt, SHA) hash.update(password) return hash.digest()
def crypt_pbkdf2_hmacsha256(salt, data): return PBKDF2(data, salt, dkLen=32, count=20000, prf=lambda p, s: HMAC.new(p, s, SHA256).digest())
def scrypt(password, salt, key_len, N, r, p, num_keys=1): """Derive one or more keys from a passphrase. Args: password (string): The secret pass phrase to generate the keys from. salt (string): A string to use for better protection from dictionary attacks. This value does not need to be kept secret, but it should be randomly chosen for each derivation. It is recommended to be at least 16 bytes long. key_len (integer): The length in bytes of every derived key. N (integer): CPU/Memory cost parameter. It must be a power of 2 and less than :math:`2^{32}`. r (integer): Block size parameter. p (integer): Parallelization parameter. It must be no greater than :math:`(2^{32}-1)/(4r)`. num_keys (integer): The number of keys to derive. Every key is :data:`key_len` bytes long. By default, only 1 key is generated. The maximum cumulative length of all keys is :math:`(2^{32}-1)*32` (that is, 128TB). A good choice of parameters *(N, r , p)* was suggested by Colin Percival in his `presentation in 2009`__: - *( 2¹⁴, 8, 1 )* for interactive logins (≤100ms) - *( 2²⁰, 8, 1 )* for file encryption (≤5s) Return: A byte string or a tuple of byte strings. .. __: http://www.tarsnap.com/scrypt/scrypt-slides.pdf """ if 2**(bit_size(N) - 1) != N: raise ValueError("N must be a power of 2") if N >= 2**32: raise ValueError("N is too big") if p > ((2**32 - 1) * 32) // (128 * r): raise ValueError("p or r are too big") prf_hmac_sha256 = lambda p, s: HMAC.new(p, s, SHA256).digest() stage_1 = PBKDF2(password, salt, p * 128 * r, 1, prf=prf_hmac_sha256) scryptROMix = _raw_scrypt_lib.scryptROMix core = _raw_salsa20_lib.Salsa20_8_core # Parallelize into p flows data_out = [] for flow in iter_range(p): idx = flow * 128 * r buffer_out = create_string_buffer(128 * r) result = scryptROMix(stage_1[idx:idx + 128 * r], buffer_out, c_size_t(128 * r), N, core) if result: raise ValueError("Error %X while running scrypt" % result) data_out += [get_raw_buffer(buffer_out)] dk = PBKDF2(password, b"".join(data_out), key_len * num_keys, 1, prf=prf_hmac_sha256) if num_keys == 1: return dk kol = [ dk[idx:idx + key_len] for idx in iter_range(0, key_len * num_keys, key_len) ] return kol
def HKDF(master, key_len, salt, hashmod, num_keys=1, context=None): """Derive one or more keys from a master secret using the HMAC-based KDF defined in RFC5869_. Args: master (byte string): The unguessable value used by the KDF to generate the other keys. It must be a high-entropy secret, though not necessarily uniform. It must not be a password. salt (byte string): A non-secret, reusable value that strengthens the randomness extraction step. Ideally, it is as long as the digest size of the chosen hash. If empty, a string of zeroes in used. key_len (integer): The length in bytes of every derived key. hashmod (module): A cryptographic hash algorithm from :mod:`Crypto.Hash`. :mod:`Crypto.Hash.SHA512` is a good choice. num_keys (integer): The number of keys to derive. Every key is :data:`key_len` bytes long. The maximum cumulative length of all keys is 255 times the digest size. context (byte string): Optional identifier describing what the keys are used for. Return: A byte string or a tuple of byte strings. .. _RFC5869: http://tools.ietf.org/html/rfc5869 """ output_len = key_len * num_keys if output_len > (255 * hashmod.digest_size): raise ValueError("Too much secret data to derive") if not salt: salt = b'\x00' * hashmod.digest_size if context is None: context = b"" # Step 1: extract hmac = HMAC.new(salt, master, digestmod=hashmod) prk = hmac.digest() # Step 2: expand t = [b""] n = 1 tlen = 0 while tlen < output_len: hmac = HMAC.new(prk, t[-1] + context + struct.pack('B', n), digestmod=hashmod) t.append(hmac.digest()) tlen += hashmod.digest_size n += 1 derived_output = b"".join(t) if num_keys == 1: return derived_output[:key_len] kol = [ derived_output[idx:idx + key_len] for idx in iter_range(0, output_len, key_len) ] return list(kol[:num_keys])
def runTest(self): key = b"\x04" * 20 one = HMAC.new(key, b"", SHA1).digest() two = HMAC.new(key, None, SHA1).digest() self.assertEqual(one, two)
private = RSA.import_key( b'-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAniD6Hta5ks4B3fyzfFPD5DdoC09O8MGC6HcaeqiA+CsQrao9\nL4VOQlzAuD2+HuHtznLTXp+Svq7g3T+k88D7JTd1KpaP254rrMS/pJy4wCCNwVks\nLqeKin6Onh9ybQFuSPURXSj3+V02qC7IlrD3zoBIOQhJTVeU3pKRgOAJz4VQAmBh\nmicIgIKrfBtDhiI9wf7GgIq5Kd8ajRbfTi7Yo9gYaiwpEUYPLB2P57dKgDh8xEw4\nWRKMfjhvgHn7eJ9AW4/iTYi/GdEvqyINoSsW9U0mxkRhlBtwUAKnmMyhm71MNJwE\nlkFEce+xd8QVDZxZ/M37l5GrtS3lNmboJP0ZWwIDAQABAoIBAEDyb3jaHbdHyKmK\nAJhIeVVTUncOuHAXMvLS9Hu7mNkVKxEBModBm96S5Q7nQR7DEd7w95LOPMH35uDI\norIBKcXj7Mo0s9pysSKRXts4CYPT+xUWUJjK9JKkn2Qfq2pNI6Rwj5SxXoQ7vla+\nfGG0Rtu4gbF3D1Bmb/0ouv1xR2ZFiEqgkS1CMJwt+DiV8RYQ/9+BOFafPtISYYgM\nwk7qo7n88N/SfIK3AiQZbPg6vJIeKfj8yYtb9DaO14phXevRaoixrbCptDUPIK4m\n5C9G9tyjEZRaRCD/kng41j4YMWb+8dBO/o06th1hKKee75FfOCWW96QhLU0JmmfW\nwmRspXECgYEAx5vXOraKk0XJ9hoyZ73asavFHY6LpLiyUDLb6XQ2lrZj7B8elJz2\nfKeMFIduyrA/HNDx5h1louj9DU5lamwvWTh6dPz+YREMTGo2tAhLf4qQa8e8qt1y\ngY/crl7Nl1lOq5C3WdIXL2+HRIFrMQy0aM/XF7UUjqcFLVQ70MH9eRECgYEAys02\ngJ4zInq6CUPRE2ZgjQ6N2UeE5znYcMJSB47ze1xJvjhtj9b99YCmOUkvVN5yaiPD\nhZMKDthaIo3A2hjoMFkgFa0tzqVlH7C/lEtsQrShSlyWCqHL7oT/1ivdPCGIKQ1g\nYHLigdjgpedsoMLWZlQMAZIqF4XcEZGEcgjhi6sCgYAxnkCTPLsXvtpkTcDH3v7U\n+ZDnNv7pdGwG2Y2m65eCQVZ3ZIjygk4XUILWu4/D3KnjnOD0xcv1AhudSiaVnMzs\nTcjK+fS15kn7WM++Uu2Jh8U8tYrlomSLZlqCEdjjTXTr2u5o6nuO9BdY5R7jM3hJ\nMZkTMJUqnMQBr5Wq3/4FMQKBgHqu1g/MpCZxk+VS70ILJtFuQoV07INszPC5vSHx\nan3wAHRgcncXmh5QKz5wdX+j6hcnd3pwzx7X5v8MPeQyORQ2dmBmmVVvXNNk+yBc\n2CsqVoBDrkjURCgQsSwA8R8VMeeTvf/awAfJCW2TqHVAKK9SnMi+gVQlmFHQdA0A\nLmFtAoGBALN6kyvF+fPP/b698Q9N5be+X43elEROreLSf03L2g66mXq9xdHBj/4w\nylkMTlUbVv2dzBRfeL8Vj8/760Vi9SngbhC+xuvRsVbv/8u1UPcPajhhHLVtD760\nwn6ji09dDmUHh6ADfGtwhD3mOjtHZA4I8peUbA6DXYkQF206Yzkr\n-----END RSA PRIVATE KEY-----', passphrase="password") public = RSA.import_key( b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAniD6Hta5ks4B3fyzfFPD\n5DdoC09O8MGC6HcaeqiA+CsQrao9L4VOQlzAuD2+HuHtznLTXp+Svq7g3T+k88D7\nJTd1KpaP254rrMS/pJy4wCCNwVksLqeKin6Onh9ybQFuSPURXSj3+V02qC7IlrD3\nzoBIOQhJTVeU3pKRgOAJz4VQAmBhmicIgIKrfBtDhiI9wf7GgIq5Kd8ajRbfTi7Y\no9gYaiwpEUYPLB2P57dKgDh8xEw4WRKMfjhvgHn7eJ9AW4/iTYi/GdEvqyINoSsW\n9U0mxkRhlBtwUAKnmMyhm71MNJwElkFEce+xd8QVDZxZ/M37l5GrtS3lNmboJP0Z\nWwIDAQAB\n-----END PUBLIC KEY-----' ) M = "Texto del cuarto apartado, cifrado RSA y HMAC (12/11/2018), formato String (cadena)" K_AB = b'01234567890ABCDEF' BLOCK_SIZE_8 = 16 # A: Mostrar por pantalla M # print(M) # A ######### A realizar por el alumno ## M = M.encode("utf-8") h = HMAC.new(K_AB, digestmod=SHA256) h.update(M) HMAC_M = h.digest() cif = PKCS1_OAEP.new(public) Cipher_M = cif.encrypt(M) # A-> B ##### No cambiar este codigo #### file_out = open("encrypted.bin", "wb") [file_out.write(x) for x in (HMAC_M, Cipher_M)] file_out.close() HMAC_M = None Cipher_M = None file_in = open("encrypted.bin", "rb") msg_HMAC_M, msg_Cipher_M = [file_in.read(x) for x in (32, -1)] # B ######### A realizar por el alumno ##