Python Crypto.Hash.HMAC.new() Examples
The following are 30
code examples of Crypto.Hash.HMAC.new().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
Crypto.Hash.HMAC
, or try the search function
.
Example #1
Source File: domcachedump.py From aumfor with GNU General Public License v3.0 | 6 votes |
def decrypt_hash(edata, nlkm, ch, xp = True): if xp: hmac_md5 = HMAC.new(nlkm, ch) rc4key = hmac_md5.digest() rc4 = ARC4.new(rc4key) data = rc4.encrypt(edata) else: # based on Based on code from http://lab.mediaservice.net/code/cachedump.rb aes = AES.new(nlkm[16:32], AES.MODE_CBC, ch) data = "" for i in range(0, len(edata), 16): buf = edata[i : i + 16] if len(buf) < 16: buf += (16 - len(buf)) * "\00" data += aes.decrypt(buf) return data
Example #2
Source File: crypto.py From cracke-dit with MIT License | 6 votes |
def decrypt(cls, key, keyusage, ciphertext): if len(ciphertext) < 24: raise ValueError('ciphertext too short') cksum, basic_ctext = ciphertext[:16], ciphertext[16:] ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest() ke = HMAC.new(ki, cksum, MD5).digest() basic_plaintext = ARC4.new(ke).decrypt(basic_ctext) exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest() ok = _mac_equal(cksum, exp_cksum) if not ok and keyusage == 9: # Try again with usage 8, due to RFC 4757 errata. ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest() exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest() ok = _mac_equal(cksum, exp_cksum) if not ok: raise InvalidChecksum('ciphertext integrity failure') # Discard the confounder. return basic_plaintext[8:]
Example #3
Source File: secretsdump.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def getHBootKey(self): LOG.debug('Calculating HashedBootKey from SAM') QWERTY = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0" DIGITS = "0123456789012345678901234567890123456789\0" F = self.getValue(ntpath.join('SAM\Domains\Account','F'))[1] domainData = DOMAIN_ACCOUNT_F(F) rc4Key = self.MD5(domainData['Key0']['Salt'] + QWERTY + self.__bootKey + DIGITS) rc4 = ARC4.new(rc4Key) self.__hashedBootKey = rc4.encrypt(domainData['Key0']['Key']+domainData['Key0']['CheckSum']) # Verify key with checksum checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY) if checkSum != self.__hashedBootKey[16:]: raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(')
Example #4
Source File: gssapi.py From cracke-dit with MIT License | 6 votes |
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 += 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
Example #5
Source File: secretsdump.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def __decryptSecret(self, key, value): # [MS-LSAD] Section 5.1.2 plainText = '' encryptedSecretSize = unpack('<I', value[:4])[0] value = value[len(value)-encryptedSecretSize:] key0 = key for i in range(0, len(value), 8): cipherText = value[:8] tmpStrKey = key0[:7] tmpKey = self.__cryptoCommon.transformKey(tmpStrKey) Crypt1 = DES.new(tmpKey, DES.MODE_ECB) plainText += Crypt1.decrypt(cipherText) key0 = key0[7:] value = value[8:] # AdvanceKey if len(key0) < 7: key0 = key[len(key0):] secret = LSA_SECRET_XP(plainText) return secret['Secret']
Example #6
Source File: secretsdump.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def __decryptLSA(self, value): if self.__vistaStyle is True: # ToDo: There could be more than one LSA Keys record = LSA_SECRET(value) tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32]) plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:]) record = LSA_SECRET_BLOB(plainText) self.__LSAKey = record['Secret'][52:][:32] else: md5 = hashlib.new('md5') md5.update(self.__bootKey) for i in range(1000): md5.update(value[60:76]) tmpKey = md5.digest() rc4 = ARC4.new(tmpKey) plainText = rc4.decrypt(value[12:60]) self.__LSAKey = plainText[0x10:0x20]
Example #7
Source File: secretsdump.py From cracke-dit with MIT License | 6 votes |
def __decryptLSA(self, value): if self.__vistaStyle is True: # ToDo: There could be more than one LSA Keys record = LSA_SECRET(value) tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32]) plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:]) record = LSA_SECRET_BLOB(plainText) self.__LSAKey = record['Secret'][52:][:32] else: md5 = hashlib.new('md5') md5.update(self.__bootKey) for i in range(1000): md5.update(value[60:76]) tmpKey = md5.digest() rc4 = ARC4.new(tmpKey) plainText = rc4.decrypt(value[12:60]) self.__LSAKey = plainText[0x10:0x20]
Example #8
Source File: secretsdump.py From cracke-dit with MIT License | 6 votes |
def __decryptSecret(self, key, value): # [MS-LSAD] Section 5.1.2 plainText = '' encryptedSecretSize = unpack('<I', value[:4])[0] value = value[len(value)-encryptedSecretSize:] key0 = key for i in range(0, len(value), 8): cipherText = value[:8] tmpStrKey = key0[:7] tmpKey = self.__cryptoCommon.transformKey(tmpStrKey) Crypt1 = DES.new(tmpKey, DES.MODE_ECB) plainText += Crypt1.decrypt(cipherText) key0 = key0[7:] value = value[8:] # AdvanceKey if len(key0) < 7: key0 = key[len(key0):] secret = LSA_SECRET_XP(plainText) return secret['Secret']
Example #9
Source File: secretsdump.py From cracke-dit with MIT License | 6 votes |
def __decryptHash(self, rid, cryptedHash, constant, newStyle = False): # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key # plus hashedBootKey stuff Key1,Key2 = self.__cryptoCommon.deriveKey(rid) Crypt1 = DES.new(Key1, DES.MODE_ECB) Crypt2 = DES.new(Key2, DES.MODE_ECB) if newStyle is False: rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack("<L",rid) + constant ) rc4 = ARC4.new(rc4Key) key = rc4.encrypt(cryptedHash['Hash']) else: key = self.__cryptoCommon.decryptAES(self.__hashedBootKey[:0x10], cryptedHash['Hash'], cryptedHash['Salt'])[:16] decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:]) return decryptedHash
Example #10
Source File: crypto.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def decrypt(cls, key, keyusage, ciphertext): if len(ciphertext) < 24: raise ValueError('ciphertext too short') cksum, basic_ctext = ciphertext[:16], ciphertext[16:] ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest() ke = HMAC.new(ki, cksum, MD5).digest() basic_plaintext = ARC4.new(ke).decrypt(basic_ctext) exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest() ok = _mac_equal(cksum, exp_cksum) if not ok and keyusage == 9: # Try again with usage 8, due to RFC 4757 errata. ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest() exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest() ok = _mac_equal(cksum, exp_cksum) if not ok: raise InvalidChecksum('ciphertext integrity failure') # Discard the confounder. return basic_plaintext[8:]
Example #11
Source File: gssapi.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
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 += 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
Example #12
Source File: crypto.py From cracke-dit with MIT License | 5 votes |
def basic_decrypt(cls, key, ciphertext): assert len(ciphertext) % 8 == 0 des = DES.new(key.contents, DES.MODE_CBC, '\0' * 8) return des.decrypt(ciphertext)
Example #13
Source File: crypto.py From cracke-dit with MIT License | 5 votes |
def decrypt(cls, key, keyusage, ciphertext): if len(ciphertext) < cls.blocksize + cls.macsize: raise ValueError('ciphertext too short') complex_plaintext = cls.basic_decrypt(key, ciphertext) cofounder = complex_plaintext[:cls.padsize] mac = complex_plaintext[cls.padsize:cls.padsize+cls.macsize] message = complex_plaintext[cls.padsize+cls.macsize:] expmac = cls.hashmod.new(cofounder+'\x00'*cls.macsize+message).digest() if not _mac_equal(mac, expmac): raise InvalidChecksum('ciphertext integrity failure') return message
Example #14
Source File: crypto.py From cracke-dit with MIT License | 5 votes |
def prf(cls, key, string): return HMAC.new(key.contents, string, SHA).digest()
Example #15
Source File: crypto.py From cracke-dit with MIT License | 5 votes |
def basic_encrypt(cls, key, plaintext): assert len(plaintext) >= 16 aes = AES.new(key.contents, AES.MODE_CBC, '\0' * 16) ctext = aes.encrypt(_zeropad(plaintext, 16)) if len(plaintext) > 16: # Swap the last two ciphertext blocks and truncate the # final block to match the plaintext length. lastlen = len(plaintext) % 16 or 16 ctext = ctext[:-32] + ctext[-16:] + ctext[-32:-16][:lastlen] return ctext
Example #16
Source File: secretsdump.py From cracke-dit with MIT License | 5 votes |
def __restore(self): # First of all stop the service if it was originally stopped if self.__shouldStop is True: LOG.info('Stopping service %s' % self.__serviceName) scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP) if self.__disabled is True: LOG.info('Restoring the disabled state for service %s' % self.__serviceName) scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4) if self.__serviceDeleted is False: # Check again the service we created does not exist, starting a new connection # Why?.. Hitting CTRL+C might break the whole existing DCE connection try: rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\pipe\svcctl]' % self.__smbConnection.getRemoteHost()) if hasattr(rpc, 'set_credentials'): # This method exists only for selected protocol sequences. rpc.set_credentials(*self.__smbConnection.getCredentials()) rpc.set_kerberos(self.__doKerberos, self.__kdcHost) self.__scmr = rpc.get_dce_rpc() self.__scmr.connect() self.__scmr.bind(scmr.MSRPC_UUID_SCMR) # Open SC Manager ans = scmr.hROpenSCManagerW(self.__scmr) self.__scManagerHandle = ans['lpScHandle'] # Now let's open the service resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName) service = resp['lpServiceHandle'] scmr.hRDeleteService(self.__scmr, service) scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP) scmr.hRCloseServiceHandle(self.__scmr, service) scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle) scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle) rpc.disconnect() except Exception, e: # If service is stopped it'll trigger an exception # If service does not exist it'll trigger an exception # So. we just wanna be sure we delete it, no need to # show this exception message pass
Example #17
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def decrypt_aescbc(ciphertext, key, iv): return unpad_pkcs7(AES.new(key, AES.MODE_CBC, iv).decrypt(ciphertext))
Example #18
Source File: crypto.py From cracke-dit with MIT License | 5 votes |
def checksum(cls, key, keyusage, text): kc = cls.enc.derive(key, pack('>IB', keyusage, 0x99)) hmac = HMAC.new(kc.contents, text, cls.enc.hashmod).digest() return hmac[:cls.macsize]
Example #19
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def encrypt_aescbc(plaintext, key, iv): plaintext = pad_pkcs7(plaintext) return AES.new(key, AES.MODE_CBC, iv).encrypt(plaintext)
Example #20
Source File: default_crypto.py From plugin.video.netflix with MIT License | 5 votes |
def sign(self, message): """Sign a message""" return base64.standard_b64encode( HMAC.new(self.sign_key, message.encode('utf-8'), SHA256).digest()).decode('utf-8')
Example #21
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def rsa_verify(s, key, sig, mod=SHA256): key = RSA.importKey(key) hash = mod.new(s) return PKCS1_v1_5_SIG.new(key).verify(hash, sig)
Example #22
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def hmac_verify(s, key, sig, mod=SHA256): hmac = HMAC.new(key, digestmod=mod) if not isinstance(s, (tuple, list)): s = (s,) for item in s: hmac.update(item) if not const_compare(hmac.digest(), sig): return False return True
Example #23
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def hmac_sign(s, key, mod=SHA256): hmac = HMAC.new(key, digestmod=mod) if not isinstance(s, (tuple, list)): s = (s,) for item in s: hmac.update(item) return hmac.digest()
Example #24
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def decrypt_oaep(ciphertext, jwk): try: return PKCS1_OAEP.new(RSA.importKey(jwk['k'])).decrypt(ciphertext) except ValueError as e: raise Error(e.args[0])
Example #25
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def encrypt_oaep(plaintext, jwk): return PKCS1_OAEP.new(RSA.importKey(jwk['k'])).encrypt(plaintext)
Example #26
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _generate_iv(enc, rng): # TODO: This would work only for A128CBC, A192CBC and A256CBC algorithms # which are only algorithms supported ATM. In case if new algorithms # support added this function should be revised. return rng(AES.block_size)
Example #27
Source File: __init__.py From lykops with Apache License 2.0 | 5 votes |
def decrypt(self, data): if not self.check_result : self.logger.error('使用AES256解密加密数据失败,原因:' + self.err_msg) return (False, self.err_msg) if not self.b_password or self.b_password is None : return (False, "加密密码为空") data = obj2bytes(data) if data[0] : data = data[1] else : return data ciphertext = unhexlify(data) b_salt, b_cryptedHmac, b_ciphertext = ciphertext.split(b"\n", 2) b_salt = unhexlify(b_salt) b_ciphertext = unhexlify(b_ciphertext) b_key1, b_key2, b_iv = self._gen_key_initctr(self.b_password, b_salt) hmacDecrypt = HMAC.new(b_key2, b_ciphertext, SHA256) if not self._is_equal(b_cryptedHmac, bytes2string(hmacDecrypt.hexdigest())): self.logger.error('使用AES256解密加密数据失败,原因:密码错误') return (False, "解密失败,密码错误") ctr = Counter.new(128, initial_value=int(b_iv, 16)) cipher = AES.new(b_key1, AES.MODE_CTR, counter=ctr) b_plaintext = cipher.decrypt(b_ciphertext) padding_length = b_plaintext[-1] b_plaintext = b_plaintext[:-padding_length] return self._handle_result(b_plaintext)
Example #28
Source File: __init__.py From lykops with Apache License 2.0 | 5 votes |
def encrypt(self, data): if not self.check_result : self.logger.error('使用AES256解密加密数据失败,原因:' + self.err_msg) return (False, self.err_msg) if not self.b_password or self.b_password is None : return (False, "加密密码为空") data = obj2bytes(data) if data[0] : b_plaintext = data[1] else : return data b_salt = os.urandom(32) b_key1, b_key2, b_iv = self._gen_key_initctr(self.b_password, b_salt) bs = AES.block_size padding_length = (bs - len(data) % bs) or bs temp = obj2bytes(padding_length * chr(padding_length)) if temp[0] : temp = temp[1] else : return temp b_plaintext += temp ctr = Counter.new(128, initial_value=int(b_iv, 16)) cipher = AES.new(b_key1, AES.MODE_CTR, counter=ctr) b_ciphertext = cipher.encrypt(b_plaintext) hmac = HMAC.new(b_key2, b_ciphertext, SHA256) b_temp_ciphertext = b'\n'.join([hexlify(b_salt), string2bytes(hmac.hexdigest()), hexlify(b_ciphertext)]) b_new_ciphertext = hexlify(b_temp_ciphertext) return self._handle_result(b_new_ciphertext)
Example #29
Source File: __init__.py From lykops with Apache License 2.0 | 5 votes |
def _gen_key_initctr(cls, b_password, b_salt): # 16 for AES 128, 32 for AES256 keylength = 32 # match the size used for counter.new to avoid extra work ivlength = 16 b_password = string2bytes(b_password) if HAS_PBKDF2HMAC: backend = default_backend() kdf = PBKDF2HMAC( algorithm=c_SHA256(), length=2 * keylength + ivlength, salt=b_salt, iterations=10000, backend=backend) b_derivedkey = kdf.derive(b_password) else: b_derivedkey = cls._create_key( b_password, b_salt, keylength, ivlength) b_key1 = b_derivedkey[:keylength] b_key2 = b_derivedkey[keylength:(keylength * 2)] b_iv = b_derivedkey[(keylength * 2):(keylength * 2) + ivlength] return b_key1, b_key2, hexlify(b_iv)
Example #30
Source File: secretsdump.py From cracke-dit with MIT License | 5 votes |
def MD5(self, data): md5 = hashlib.new('md5') md5.update(data) return md5.digest()