def certify(): if(len(sys.argv)!=2): return privf=sys.argv[1] f=open(privf,'rb') privkey=RSA.importKey(f.read()) f.close() f=urllib.urlopen('http://verify.wujianguo.org/publickey') pubkey=RSA.importKey(f.read()) f.close() text=MD5.new(Crypto.Random.get_random_bytes(128)).digest() # print(text) info='*****@*****.**'+text # info='*****@*****.**'+text signature=privkey.sign(text,'') encinfo=pubkey.encrypt(info,32) # print(signature) # print(encinfo) para=urllib.urlencode({'info':encinfo,'text':signature}) f=urllib.urlopen('http://verify.wujianguo.org/doverify',para) # print(f.read()) s=f.read() # print(s) if MD5.new(text).digest()==privkey.decrypt(eval(s)): print "OK" else: print "ERROR" f.close()
def decode(cDataStr, token, n): if (len(cDataStr) < 32): return False crc = cDataStr[0:32] cData = b64decode(cDataStr[32:]) hasher = MD5.new() hasher.update(token) key = hasher.hexdigest() cipher = Blowfish.new(key) try: dataStr = cipher.decrypt(cData) except: return False checkCrc = MD5.new() checkCrc.update(cData) if (crc != checkCrc.hexdigest()): return False data = dataStr.split('|') if (len(data) != 6): return False tLen = len(data[5]) pLen = ord(data[5][tLen-1]) nStr = data[5][0:tLen-pLen] if (nStr != str(n)): return False return [data[0], data[1], data[2], data[3], data[4]]
def current_exp_list(self, client_tag): exp_list = list() exp_list += self.client_exps[client_tag] exp_list += [os.path.basename(path) + "%" + MD5.new(open(path,'r').read()).digest() for path in glob.glob(os.path.join(conf['experiments_dir'], '*.cfg'))] exp_list += [os.path.basename(path) + "%" + MD5.new(open(path,'r').read()).digest() for path in glob.glob(os.path.join(conf['experiments_dir'], '*.py' ))] return exp_list
def key_from_password(password, salt=_salt, iterations=_iterations): """Imitate java's PBEWithMD5AndDES algorithm to produce a DES key""" from Crypto.Hash import MD5 hasher = MD5.new() hasher.update(password) hasher.update(salt) result = hasher.digest() for i in range(1, iterations): hasher = MD5.new() hasher.update(result) result = hasher.digest() # test = ' '.join([str( unsigned ) for unsigned in [ord(character) for character in result]]) # print test key = result[:8] # TODO: Not likely, but may need to adjust for twos complement in java # For DES keys, LSB is odd parity for the key def set_parity(v): def num1s_notlsb(x): return sum([x & (1 << i) > 0 for i in range(1, 8)]) def even_parity(x): return num1s_notlsb(x) % 2 == 0 return v | 0b1 if even_parity(v) else v & 0b11111110 return "".join([chr(set_parity(ord(digit))) for digit in key])
def _setPKCSKeys(self, salt): h = MD5.new(self._pwd) h.update(salt) for i in xrange(1, self._iterations): h = MD5.new(h.digest()) dk = h.digest() self._kv = dk[0:8] self._iv = dk[8:]
def key(password, salt, iterations): hasher = MD5.new() hasher.update(password) hasher.update(salt[:8]) result = hasher.digest() for _ in range(1, iterations): hasher = MD5.new() hasher.update(result) result = hasher.digest() return result
def newkeys(self): """Generate a new Secret/Public key and write them to the configured files. In the case of the Secret Key, it's appended to Secring. The Public Key overwrites the existing file. """ log.debug("Generating new keypair") keyobj = RSA.generate(1024) #public = RSA.public(keyobj) secret, public = self.rsaobj2mix(keyobj) keyid = MD5.new(data=public[2:258]).hexdigest() log.info("Generated new Secret Key with Keyid: %s", keyid) iv = Crypto.Random.get_random_bytes(8) pwhash = MD5.new(data=config.get('general', 'passphrase')).digest() des = DES3.new(pwhash, DES3.MODE_CBC, IV=iv) secenc = des.encrypt(secret) today = timing.today() expire = timing.datestamp(timing.future( days=config.getint('keys', 'validity_days'))) f = open(config.get('keys', 'secring'), 'a') f.write('-----Begin Mix Key-----\n') f.write('Created: %s\n' % today) f.write('Expires: %s\n' % expire) f.write('%s\n' % keyid) f.write('0\n') f.write('%s' % iv.encode('base64')) f.write('%s\n' % self.wrap(secenc.encode("base64"), 40)) f.write('-----End Mix Key-----\n\n') f.close() log.debug("Secret Key written to %s", config.get('keys', 'secring')) f = open(config.get('keys', 'pubkey'), 'w') f.write('%s ' % config.get('general', 'shortname')) f.write('%s ' % config.get('mail', 'address')) f.write('%s ' % keyid) f.write('2:%s ' % config.get('general', 'version')) if config.getboolean('general', 'middleman'): conf = "MC" else: conf = "C" f.write('%s ' % conf) f.write('%s %s\n\n' % (today, expire)) f.write('-----Begin Mix Key-----\n') f.write('%s\n' % keyid) f.write('%s\n' % len(public)) f.write('%s\n' % self.wrap(public.encode("base64"), 40)) f.write('-----End Mix Key-----\n\n') f.close() log.debug("Public Key written to %s", config.get('keys', 'pubkey'))
def client_rsa_session_key(self, ADDR): #Establish key session with the server #Receive the server's publickey later on to be used for encryption server_public = pickle.loads(self.socket.recv(4096)) print 'Received server\'s public key: '+str(server_public) #Create keys and send the public key to server random_gen = Random.new().read client_key = RSA.generate(self.KEY_LENGTH, random_gen) client_public = client_key.publickey() self.socket.sendto(pickle.dumps(client_public), ADDR) #Receive the session key from the server sessionkey_data = pickle.loads(self.socket.recv(4096)) encrypted_sessionkey = sessionkey_data[0] server_signature = sessionkey_data[1] #Decrypt the session key with client's private key sessionkey = client_key.decrypt(encrypted_sessionkey) #Verify the signature with the decreypted session key hash_decrypted = MD5.new(sessionkey).digest() if not server_public.verify(hash_decrypted, server_signature): print 'Session key is corrupted! Ending session now.' sys.exit() return sessionkey
def get_lsa_key(secaddr, bootkey): root = get_root(secaddr) if not root: return None enc_reg_key = open_key(root, ["Policy", "PolSecretEncryptionKey"]) if not enc_reg_key: return None enc_reg_value = enc_reg_key.ValueList.List[0] if not enc_reg_value: return None obf_lsa_key = secaddr.read(enc_reg_value.Data.value, enc_reg_value.DataLength.value) if not obf_lsa_key: return None md5 = MD5.new() md5.update(bootkey) for i in range(1000): md5.update(obf_lsa_key[60:76]) rc4key = md5.digest() rc4 = ARC4.new(rc4key) lsa_key = rc4.decrypt(obf_lsa_key[12:60]) return lsa_key[0x10:0x20]
def load_secrets(self, plan=None): """ Loads secrets attached to this fittings plan :param plan: the file that contains fittings plan :type plan: ``str`` or ``file`` or ``dict`` or ``list`` of ``dict`` """ if plan: secretsId = MD5.new(plan).hexdigest() elif self.secretsId: secretsId = self.secretsId else: return secretsFile = secretsId+'.secrets' logging.debug("Loading secrets from '{}'".format(secretsFile)) if os.path.isfile(secretsFile): try: handle = open(secretsFile, 'r') self.secrets = yaml.load(handle) handle.close() logging.debug("- found {} secrets".format( len(self.secrets))) except IOError: logging.debug("- unable to load secrets")
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 forget_secrets(self, plan=None): """ Destroys secrets attached to this fittings plan """ if plan: secretsId = MD5.new(plan).hexdigest() elif self.secretsId: secretsId = self.secretsId else: return secretsFile = secretsId+'.secrets' if self.safeMode: logging.info("Secrets cannot be forgotten in safe mode") self.secrets = {} if os.path.isfile(secretsFile): try: os.remove(secretsFile) except IOError: logging.warning("Unable to forget secrets") logging.debug("- cannot delete file '{}'".format( secretsFile))
def __openssl_kdf(self, req): """We need 32 bytes for the AES key, and 16 bytes for the IV""" prev = '' while req>0: prev = MD5.new(prev+self.secret+self.salt).digest() req -= 16 yield prev
def save_secrets(self, plan=None): """ Saves secrets attached to this fittings plan :param plan: the file that contains fittings plan :type plan: ``str`` or ``file`` or ``dict`` or ``list`` of ``dict`` """ if plan: secretsId = MD5.new(plan).hexdigest() elif self.secretsId: secretsId = self.secretsId else: return secretsFile = secretsId+'.secrets' try: handle = open(secretsFile, 'w') for id in self.secrets: handle.write("{}: '{}'\n".format( id, self.secrets[id].replace('\n', '\\n'))) handle.close() except IOError: logging.warning("Unable to save secrets") logging.debug("- cannot write to file '{}'".format( secretsFile))
def ds_decrypt_with_pek(pek, enc_hash): md5=MD5.new() md5.update(pek) md5.update(enc_hash[0:16]) rc4_key=md5.digest(); rc4 = ARC4.new(rc4_key) return rc4.encrypt(enc_hash[16:])
def compress_and_encrypt(input_string, key): hashed = MD5.new() hashed.update(key) compressed = zlib.compress(input_string) encryptor = AES.new(hashed.digest(), AES.MODE_CBC, '3aa349e1d3552b44') ciphertext = encryptor.encrypt(pad_to_sixteen(compressed)) return ciphertext
def _EVP_BytesToKey(data, salt, key_len): d = [ b'' ] m = (key_len + 15 ) // 16 for _ in range(m): nd = MD5.new(d[-1] + data + salt).digest() d.append(nd) return b"".join(d)[:key_len]
def decrypt_and_decompress(input_string, key): hashed = MD5.new() hashed.update(key) decryptor = AES.new(hashed.digest(), AES.MODE_CBC, '3aa349e1d3552b44') decrypted = decryptor.decrypt(input_string) decompressed = zlib.decompress(decrypted) return decompressed
def _GetLSAKey(self, registry, boot_key): """Retrieves the LSA key. Args: registry (dfwinreg.WinRegistry): Windows Registry. boot_key (bytes): boot key. Returns: bytes: LSA key or None if not found. """ policy_encryption_key = registry.GetKeyByPath( self._POLICY_ENCRYPTION_KEY_PATH) if not policy_encryption_key: return None policy_encryption_value = policy_encryption_key.GetValueByName('') if not policy_encryption_value: return None value_data = policy_encryption_value.data md5 = MD5.new() md5.update(boot_key) iteration = 0 while iteration < 1000: md5.update(value_data[60:76]) iteration += 1 rc4_key = md5.digest() rc4 = ARC4.new(rc4_key) decrypted_data = rc4.decrypt(value_data[12:60]) return decrypted_data[16:32]
def check(ip): checkflag=genflag() key=RSA.construct((n,e,d,p,q,u),) flag_md5=MD5.new(checkflag).digest() signature=key.sign(flag_md5,'')[0] try: opener = urllib2.build_opener() opener.addheaders = [('User-agent', USERAGENT)] f=opener.open('http://%s:3255/add.py?text=%s&sig=%s'%(ip,checkflag,signature), timeout=10) if f.getcode()!=200: return MUMBLE checkflag=checkflag[:-1]+"%%%02x" % ord(checkflag[-1]) try: f=opener.open('http://%s:3255/del.py?text=%s'%(ip,checkflag), timeout=5) if f.getcode()!=200: return MUMBLE except: pass # ignore f=opener.open('http://%s:3255/?c=%s'%(ip,genflag()), timeout=5) if f.getcode()!=200: return MUMBLE except Exception as E: print("%s"%E) return NOCONNECT return OK;
def md5_hash_encode(cleartext): """ MD5 any arbitrary input. Returns the 16-digit hexidecimal hash as a 32-char string. e.g. md5_hash_encode("Hello, world!") = '6cd3556deb0da54bca060b4c39479839' """ from Crypto.Hash import MD5 return MD5.new(cleartext).hexdigest()
def run(self, message, aes_key=None, encrypt=False): if not aes_key: aes_key = "this_is_so_secure" key = MD5.new(aes_key).hexdigest() aes_handler = AES.new(key, AES.MODE_CBC, 'Save the kittens') if encrypt: padding = 16 - (len(message) % 16) message += chr(padding) * padding result = { 'message': base64.b64encode(aes_handler.encrypt(message)) } return json.dumps(result) else: message = base64.b64decode(message) decrypted_message = aes_handler.decrypt(message) unpadded_message = decrypted_message[:- ord(decrypted_message[-1])] result = { 'message': unpadded_message } return json.dumps(result)
def decrypt(cipherText, password): time_s = time.time() cipherText = cipherText.decode('hex') # Generate key from password key = MD5.new(password).hexdigest().decode('hex') # Decrypt the ciphertext iv = cipherText[:16] # iv = ('ee445d5f8169204c77d445aa4688eae7').decode('hex') dec = cipherText[16:] aes = AES.new(key, AES.MODE_CBC, iv) decrypted = aes.decrypt(dec) # print "%s" % decrypted # Extract the hash, pattern and time para = decrypted.split('###') if len(para) < 4: return False hash_recv, pattern_recv, time_recv = para[0], para[1], para[2] # compare hash hash_s = SHA.new(pattern_recv + time_recv).hexdigest() if hash_s != hash_recv: # print "hash doesn't match!" return False # compare time time_recv = float(time_recv) / 1000 if time_s - time_recv > 20 or time_s < time_recv: # print "Invalid time!" return False return pattern_recv
def __init__(self, key, backend): self.backend = backend key = MD5.new(key).digest() self.random = Random.new() # We want to use self-synchronizing feature of CBC, so the IV # is trivial in fact, but for security consideration, we # should give it a random value. iv = self.random.read(block_size) self.send_cipher = AES.new(key, AES.MODE_CBC, iv) self.recv_cipher = AES.new(key, AES.MODE_CBC, iv) # initialize record layer buffers self.cipher_buf = b"" self.plain_buf = b"" self.recv_synchornized = False self.first_packet_checked = False self.header_arrived = False self.secure_closed = False self.closed = False # part packet buffer self.part_packet = b"" # The first block must not contain any useful data or it will # never be recognized, so we send one block here. However, # it is only required to be received before the first data # block, so it is not necessary to be sent instantaneously. data = self.random.read(block_size) data = self.send_cipher.encrypt(data) backend.send(data, False)
def main(): if len(sys.argv) != 3: print (" Usage: <domainfile> <key> ") return 1 domain_file = sys.argv[1] key = bytes(sys.argv[2], 'utf-8') md5key = MD5.new(key).digest() cipher = ARC4.new(md5key) with open(domain_file, 'rb') as f: data = f.read() # Decrypt RC4 Data data_dec = cipher.decrypt(data) with open('decrypt', 'wb') as f: f.write(data_dec) print('Data writen to decrypt file.') # Añadimos la cabecera GZIP para que pueda ser descomprimido con gzip data2 = b"\x1f\x8b\x08\x00\x00\x00\x00\x00" + data_dec # data2 = data_dec with open('deflate.gz', 'wb') as f: f.write(data2) print('Data writen to deflate.gz file. Pleas use zcat') return 0
def from_file(cls, filename, password=None, padding='{'): with open(filename, 'r') as fd: encoded_key = fd.read() if password: h = MD5.new() h.update(password.encode('utf-8')) secret = h.hexdigest() cipher = AES.new(secret) # decode the encoded string try: decoded = KeyMgmt.decode_AES(cipher, encoded_key, padding) except Exception as e: log.error('Failed to decode Keyfile: %s', e) raise if decoded is None: raise Exception('Failed to decode Keyfile') #s = io.StringIO(decoded) #cls.key = s.readline().strip() #cls.secret = s.readline().strip() #s.close() key, secret = decoded.splitlines()[:2] return cls(key, secret)
def verifyMessage(key,message,signature): hash = MD5.new(message).digest() # print hash try: return key.verify(hash,signature) except ValueError: print "Value Error" # keys = generateKeys() # message = "Hello World" # # seq2 = asn1.DerSequence() # data = "\n".join(keys[0].strip().split("\n")[1:-1]).decode("base64") # seq2.decode(data) # p, q, g, y, x = seq2[1:] # key2 = DSA.construct((y, g, p, q, x)) # # seq2 = asn1.DerSequence() # data = "\n".join(keys[1].strip().split("\n")[1:-1]).decode("base64") # seq2.decode(data) # p, q, g, y = seq2[1:] # key3 = DSA.construct((y, g, p, q)) # # signed = signMessage(key2,message) # print signed # print verifyMessage(key3,message,signed)
def attachments(request, report_id): if request.method == "POST": report = Report.objects.get(id=report_id) f = AttachmentForm(request.POST, request.FILES) # check whether it's valid: print('upload' in request.FILES) if f.is_valid(): # Save the form data to the database. # But dont yet commit, we still have some data to add. attachment = f.save(commit=False) attachment.upload_date = timezone.now() attachment.report = report # NOW we can save attachment.save(); h = MD5.new() chunk_size = 8192 with open(attachment.upload.path, 'rb') as f: while True: chunk = f.read(chunk_size) if len(chunk) == 0: break h.update(chunk) attachment.key = h.hexdigest() attachment.save() messages.success(request, 'Attachment added!') return render(request, 'reports/read_report.html', {'report': report, "attachment_form": AttachmentForm()}) else: messages.warning(request, 'Attachment failed to add!') return render(request, 'reports/read_report.html', {'report': report, "attachment_form": f})
def get_hbootkey(samaddr, bootkey): sam_account_path = ["SAM", "Domains", "Account"] if not bootkey: return None root = rawreg.get_root(samaddr) if not root: return None sam_account_key = rawreg.open_key(root, sam_account_path) if not sam_account_key: return None F = None for v in rawreg.values(sam_account_key): if v.Name == 'F': F = samaddr.read(v.Data, v.DataLength) if not F: return None md5 = MD5.new() md5.update(F[0x70:0x80] + aqwerty + bootkey + anum) rc4_key = md5.digest() rc4 = ARC4.new(rc4_key) hbootkey = rc4.encrypt(F[0x80:0xA0]) return hbootkey
def get_messages(): json_query = {} json_query['method'] = 'get_messages' json_query['id'] = '0' json_query['params'] = {'kiosk-id': Beagleboard.get_dieid()} json_query_str = json.dumps(json_query) logger.debug("Sending JSON Query: %s" % json_query_str) hash = MD5.new(json_query_str).digest() # encoding signature encoded_sig = Security.sign_digest(hash) headers = {'X-eko-signature': encoded_sig} urlreq = urllib2.Request(Constants.URLJsonAPI, json_query_str, headers) try: response = urllib2.urlopen(urlreq) except urllib2.URLError: logger.exception("Unable to open URL to fetch server messages") return False json_reply = response.read() try: response_dict = json.loads(json_reply) except: logger.exception("Unable to decode response JSON!") return False messages = response_dict['result'] return messages
def XeCryptMd5(*args: Union[bytes, bytearray]) -> bytes: hasher = MD5.new() [hasher.update(x) for x in args] return hasher.digest()
def hash(self, string): m = MD5.new("fgsudyf67") m.update(string) return m.hexdigest()
def check_md5_sum(): f = open('test_file') hashsum = MD5.new() hashsum.update(f.read()) self.assertEqual(hashsum.hexdigest(), "4ca2aafb4101c1e42235aad24fbb83be")
# 파이썬 실습 파일: 2-5.hash.py from Crypto.Hash import MD5, RIPEMD, SHA, SHA256 msg = '이 문서의 Hash value를 계산한다?' print("\nMessage : ", msg) msg = msg.encode() # MD5 h = MD5.new() h.update(msg) hv = h.hexdigest() print("\n MD5 (%d bit) : %s" % (len(hv) * 4, hv)) # RIPEMD160 h = RIPEMD.new() h.update(msg) hv = h.hexdigest() print(" RIPEMD (%d bit) : %s" % (len(hv) * 4, hv)) # SHA h = SHA.new() h.update(msg) hv = h.hexdigest() print(" SHA (%d bit) : %s" % (len(hv) * 4, hv)) # SHA256 h = SHA256.new() h.update(msg) hv = h.hexdigest() print(" SHA256 (%d bit) : %s" % (len(hv) * 4, hv))
def _MAC_hash(mac_str): """ Returns MAC hash value in uppercase hexadecimal form and truncated to 32 characters. """ return MD5.new(mac_str).hexdigest().upper()[:32]
def decrypt_data(self, value, iv): value = base64.b64decode(value) iv = MD5.new("%s!%s" % (iv, settings.SECRET_KEY)).digest() dec = AES.new(settings.SECRET_KEY[:32], AES.MODE_CBC, iv) return dec.decrypt(value).strip()
# s1和s2和r需要手动输入 # When I behold the violet past prime # (476285682163840111134589069951095433451762033212L, 750878836594769714218369688081048654723959920310L) s1 = 695867118826234288019728061102190345510870577729L # Born on the bier with white and bristly beard # (476285682163840111134589069951095433451762033212L, 1024301092383298645166193780198072718145056142558L) s2 = 1189095586470437230337352901845581329066775460494L r = 72901494132238706242193413574196007501544879148L m1 = number.bytes_to_long(MD5.new(msg1).digest()) m2 = number.bytes_to_long(MD5.new(msg2).digest()) x = (s2 * m1 - s1 * m2) * gm.invert(s1 * r - s2 * r, q) % q y = gm.powmod(g, x, p) key = DSA.generate(1024) #k = random.getrandbits(50) k = 517796658309687953755760389310 key.g = g key.p = p key.q = q
def lian_verify(data, sgn): content = to_content(data, verf_skip_keys) h = HASH.new(content) sgn = base64.decodestring(sgn) return lian_signer.verify(h, sgn)
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 += 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 MD5(self, x): h = MD5.new() h.update(x.encode("utf-8")) x = h.hexdigest() x = int(h.hexdigest(), 16) return x
from Crypto.Hash import SHA512 from Crypto.Hash import SHA384 from Crypto.Hash import SHA256 from Crypto.Hash import SHA224 from Crypto.Hash import RIPEMD from Crypto.Hash import MD5 from Crypto.Hash import MD4 from Crypto.Hash import MD2 a = raw_input("Digite a string: ") b = SHA512.new(a).hexdigest() c = SHA384.new(a).hexdigest() d = SHA256.new(a).hexdigest() e = SHA224.new(a).hexdigest() f = RIPEMD.new(a).hexdigest() g = MD5.new(a).hexdigest() h = MD4.new(a).hexdigest() i = MD2.new(a).hexdigest() print "SHA512 = ", b print "SHA384 = ", c print "SHA256 = ", d print "SHA224 = ", e print "RIPEMD160 = ", f print "MD5 = ", g print "MD4 = ", h print "MD2 = ", i
def build_codeword(ID, trapdoor): ID_index = MD5.new() ID_index.update(str(ID)) ECB_cipher = AES.new(trapdoor, AES.MODE_ECB) return ECB_cipher.encrypt(ID_index.digest()).encode("hex")
def getSymTimings(self, testString): """ Executes the different types of symetric encryption algorithms on given string """ # RSA rp = randpool.RandomPool() t1 = time.time() rsaKey = RSA.generate(1024, rp.get_bytes) t2 = time.time() print 'RSA key generation took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = rsaKey.encrypt(testString, "") t2 = time.time() print 'RSA encryption took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = rsaKey.decrypt(encString) t2 = time.time() print 'RSA decryption took: %0.3fms.' % ((t2 - t1) * 1000.) # DSA rp = randpool.RandomPool() t1 = time.time() dsaKey = DSA.generate(1024, rp.get_bytes) t2 = time.time() print 'DSA key generation took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = dsaKey.sign(testString, 1024) t2 = time.time() print 'DSA signing took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() hash = MD5.new(testString).digest() encString = dsaKey.verify(hash, encString) t2 = time.time() print 'DSA verifying took: %0.3fms.' % ((t2 - t1) * 1000.) # AES t1 = time.time() aesKey = AES.new('abcdabcdabcdabcdabcdabcdabcdabcd') t2 = time.time() print 'AES key generation took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = aesKey.encrypt(testString) t2 = time.time() print 'AES encryption took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = aesKey.decrypt(encString) t2 = time.time() print 'AES decryption took: %0.3fms.' % ((t2 - t1) * 1000.) # DES t1 = time.time() desKey = DES.new('abcdabcd') t2 = time.time() print 'DES key generation took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = desKey.encrypt(testString) t2 = time.time() print 'DES encryption took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = desKey.decrypt(encString) t2 = time.time() print 'DES decryption took: %0.3fms.' % ((t2 - t1) * 1000.) # DES3 t1 = time.time() des3Key = DES3.new('abcdabcdabcdabcd') t2 = time.time() print 'DES3 key generation took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = des3Key.encrypt(testString) t2 = time.time() print 'DES3 encryption took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = des3Key.decrypt(encString) t2 = time.time() print 'DES3 decryption took: %0.3fms.' % ((t2 - t1) * 1000.) # Blowfish t1 = time.time() blowfishKey = Blowfish.new('abcdabcdabcdabcdabcdabcdabcdabcd') t2 = time.time() print 'Blowfish key generation took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = blowfishKey.encrypt(testString) t2 = time.time() print 'Blowfish encryption took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = blowfishKey.decrypt(encString) t2 = time.time() print 'Blowfish decryption took: %0.3fms.' % ((t2 - t1) * 1000.) # RC5 t1 = time.time() rc5Key = RC5.new('abcdabcdabcdabcd') t2 = time.time() print 'RC5 key generation took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = rc5Key.encrypt(testString) t2 = time.time() print 'RC5 encryption took: %0.3fms.' % ((t2 - t1) * 1000.) t1 = time.time() encString = rc5Key.decrypt(encString) t2 = time.time() print 'RC5 decryption took: %0.3fms.' % ((t2 - t1) * 1000.)
def getSignature(self, msg): hash_of_my_msg = MD5.new(msg).digest() my_signature = self.my_keypair.sign(hash_of_my_msg, '') return my_signature
subprocess.check_call([sys.executable, "setup.py", "build"], stdout=devnull) print "-- Installing pycrypto" subprocess.check_call( [sys.executable, "setup.py", "install", "--prefix=install"], stdout=devnull) print "-- Testing pycrypto" sys.path.append("install/site-packages") test_string = "test string".ljust(16) from Crypto.Hash import SHA256, MD5 assert SHA256.new(test_string).hexdigest( ) == "edce3184097ede907d91c4069c55104785a3a989b9706e5919202d6f5fe2d814" assert MD5.new(test_string).hexdigest() == "e135865bb047e78e1827b0cf83696725" from Crypto.Cipher import AES aes1 = AES.new("pwd1__0123456789") aes2 = AES.new("pwd2__0123456789") enc_data = aes1.encrypt(test_string) enc_data2 = aes2.encrypt(test_string) assert enc_data != enc_data2 assert aes1.decrypt(enc_data) == test_string assert aes2.decrypt(enc_data2) == test_string from Crypto.PublicKey import RSA from Crypto import Random key = RSA.generate(1024, Random.new().read) public_key = key.publickey() enc_data = public_key.encrypt(test_string, 32)
def check_md5_sum(): f = open('test_file') hashsum = MD5.new() hashsum.update(f.read()) self.assertEqual(hashsum.hexdigest(), "e5941d615f53312fd66638239c1f90d5")
from cryptography.hazmat.primitives import hashes from Crypto.Hash import MD2 as pycrypto_md2 from Crypto.Hash import MD4 as pycrypto_md4 from Crypto.Hash import MD5 as pycrypto_md5 import hashlib hashlib.md5(1) hashlib.md5(1).hexdigest() abc = str.replace(hashlib.md5("1"), "###") print(hashlib.md5("1")) pycrypto_md2.new() pycrypto_md4.new() pycrypto_md5.new() hashes.MD5()
def digest(algorithm=_DEFAULT_HASH_ALGORITHM, hash_library=_DEFAULT_HASH_LIBRARY): """ <Purpose> Provide the caller with the ability to create digest objects without having to worry about hash library availability or which library to use. The caller also has the option of specifying which hash algorithm and/or library to use. # Creation of a digest object using defaults # or by specifying hash algorithm and library. digest_object = tuf.hash.digest() digest_object = tuf.hash.digest('sha384') digest_object = tuf.hash.digest('pycrypto') # The expected interface for digest objects. digest_object.digest_size digest_object.hexdigest() digest_object.update('data') digest_object.digest() # Added hash routines by this module. digest_object = tuf.hash.digest_fileobject(file_object) digest_object = tuf.hash.digest_filename(filename) <Arguments> algorithm: The hash algorithm (e.g., md5, sha1, sha256). hash_library: The library providing the hash algorithms (e.g., pycrypto, hashlib). <Exceptions> tuf.UnsupportedAlgorithmError tuf.UnsupportedLibraryError <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm) or algorithm.new() # pycrypto). """ # Was a hashlib digest object requested and is it supported? # If so, return the digest object. if hash_library == 'hashlib' and hash_library in _supported_libraries: try: return hashlib.new(algorithm) except ValueError: raise tuf.UnsupportedAlgorithmError(algorithm) # Was a pycrypto digest object requested and is it supported? elif hash_library == 'pycrypto' and hash_library in _supported_libraries: # Pycrypto does not offer a comparable hashlib.new(hashname). # Let's first check the 'algorithm' argument before returning # the correct pycrypto digest object using pycrypto's object construction. if algorithm == 'md5': return MD5.new() elif algorithm == 'sha1': return SHA.new() elif algorithm == 'sha224': return SHA224.new() elif algorithm == 'sha256': return SHA256.new() elif algorithm == 'sha384': return SHA384.new() elif algorithm == 'sha512': return SHA512.new() else: raise tuf.UnsupportedAlgorithmError(algorithm) # The requested hash library is not supported. else: raise tuf.UnsupportedLibraryError('Unsupported library requested. ' 'Supported hash libraries: ' + str(_SUPPORTED_LIB_LIST))
def findindex(self, key): from Crypto.Hash import MD5 h = MD5.new() h.update(key.encode("utf-8")) h = int(h.hexdigest(), 16) return h
def chat_client(): last_time_message = 0 #if(len(sys.argv) == 2) : # print 'Usage : python chat_client.py hostname port' # sys.exit() if IS_TCP: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) # connect to remote host try: s.connect(ADDR) except: print 'Unable to connect' sys.exit() else: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #Establish key session with the server #Receive the server's publickey later on to be used for encryption server_public = pickle.loads(s.recv(4096)) print 'Received server\'s public key: ' + str(server_public) #Create keys and send the public key to server KEY_LENGTH = 1024 # Key size (in bits) random_gen = Random.new().read client_key = RSA.generate(KEY_LENGTH, random_gen) client_public = client_key.publickey() s.sendto(pickle.dumps(client_public), ADDR) #Receive the session key from the server sessionkey_data = pickle.loads(s.recv(4096)) #split = sessionkey_data.split(';hmac=') encrypted_sessionkey = sessionkey_data[0] server_signature = sessionkey_data[1] #Decrypt the session key with client's private key sessionkey = client_key.decrypt(encrypted_sessionkey) #Verify the signature with the decreypted session key hash_decrypted = MD5.new(sessionkey).digest() if not server_public.verify(hash_decrypted, server_signature): print 'Session key is corrupted! Ending session now.' sys.exit() #Send in the authenication with symmetric encryption authentication_info = username + ";password="******";" padding = (int)(float(16 * (int)(len(authentication_info) / 16 + 1))) # float(16*(int)(100/16+1)) = 112 authentication_info = authentication_info.ljust(padding) encryption_suite = AES.new(sessionkey, AES.MODE_CBC, 'This is an IV456') cipher_text = encryption_suite.encrypt(authentication_info) digest_maker = hmac.new(sessionkey, cipher_text, hashlib.sha1) final_message = (cipher_text, digest_maker.hexdigest()) s.send(pickle.dumps(final_message)) print 'Commands: \n/onlineusers --> Get user online \n /block <username> --> Block person' print 'Connected to remote host. You can start sending messages' sys.stdout.write('') sys.stdout.flush() while 1: socket_list = [sys.stdin, s] # Get the list sockets which are readable ready_to_read, ready_to_write, in_error = select.select( socket_list, [], []) for sock in ready_to_read: if sock == s: # incoming message from remote server, s if IS_TCP: data = sock.recv(4096) else: data, server = sock.recvfrom(4096) if not data: print '\nDisconnected from chat server' sys.exit() else: #Decrypt the message if the user has indicated password if data[0:7] != 'Server>' and key != '' and IS_CHECK_AUTH: #Try decrypt with key i.e. the group chat key #If the verification with the key didn't work, then try with session key to see if it is message from the server #Read in the hmac split = data.split(';hmac=') data = split[0] mac = split[1] #Verify the mac on the data expected_mac = hmac.new(key, data, hashlib.sha1) if hmac.compare_digest(expected_mac.hexdigest(), mac): # Decryption decryption_suite = AES.new(key, AES.MODE_CBC, 'This is an IV456') plain_text = decryption_suite.decrypt(data) #Verify no one has replayed this message, by checking the timestamp and the current time matchObj = re.match(r'\[([0-9]+)\.*[0-9]*\].*', plain_text) if matchObj: #if the last time a message was received is greater than this message timestamp, then the message was replayed if long(matchObj.group(1)) < last_time_message: print "And the message was also replayed." else: last_time_message = long(matchObj.group(1)) sys.stdout.write('\n' + plain_text) else: #Try to decrypt with sessionkey; it might be server message expected_mac = hmac.new(sessionkey, data, hashlib.sha1) if hmac.compare_digest(expected_mac.hexdigest(), mac): decryption_suite = AES.new( sessionkey, AES.MODE_CBC, 'This is an IV456') plain_text = decryption_suite.decrypt(data) sys.stdout.write('\n' + plain_text) else: print "\nWarning! The following message has been tampered with OR you dont have the right key." else: #print data sys.stdout.write('\n' + data) sys.stdout.write('\n') sys.stdout.flush() else: # user entered a message msg = sys.stdin.readline() if key != '' and IS_CHECK_AUTH: #Encrypt messages with the session key if the message is for the server if isServerCommand(msg): whole_message = msg + ";" padding = (int)(float( 16 * (int)(len(whole_message) / 16 + 1))) # float(16*(int)(100/16+1)) = 112 whole_message = whole_message.ljust(padding) #Encryption encryption_suite = AES.new(sessionkey, AES.MODE_CBC, 'This is an IV456') cipher_text = encryption_suite.encrypt(whole_message) digest_maker = hmac.new(sessionkey, cipher_text, hashlib.sha1) final_message = cipher_text + ';hmac=' + digest_maker.hexdigest( ) s.send(final_message) else: whole_message = "[" + str( time()) + "]" + username + ">" + msg padding = (int)(float( 16 * (int)(len(whole_message) / 16 + 1))) # float(16*(int)(100/16+1)) = 112 whole_message = whole_message.ljust(padding) #Encryption encryption_suite = AES.new(key, AES.MODE_CBC, 'This is an IV456') cipher_text = encryption_suite.encrypt(whole_message) digest_maker = hmac.new(key, cipher_text, hashlib.sha1) final_message = cipher_text + ';hmac=' + digest_maker.hexdigest( ) if IS_TCP: s.send(final_message) else: s.sendto(final_message, ADDR) else: #Do not encrypt if the user didn't specify anything for the password final_message = "[" + str( time()) + "]" + username + ">" + msg if IS_TCP: s.send(final_message) else: s.sendto(final_message, ADDR) sys.stdout.write('Me>' + msg) sys.stdout.flush()
def Hash(self, key): from Crypto.Hash import MD5 h = MD5.new() h.update(key.encode('utf-8')) new_key=int(h.hexdigest(),16) return new_key
def my_hash(data): return MD5.new(data.encode('utf-8'))
def encrypt_data(self, value, iv): iv = MD5.new("%s!%s" % (iv, settings.SECRET_KEY)).digest() enc = AES.new(settings.SECRET_KEY[:32], AES.MODE_CBC, iv) # Guess why :32? value = enc.encrypt(self.pad_string(value, AES.block_size)) return base64.b64encode(value)
def hashKey(key): key = str(key).encode() md5 = MD5.new() md5.update(key) return md5.hexdigest()
def hashMD5(data): md5Hash = MD5.new() md5Hash.update(data) hash = md5Hash.digest() return hash
if not os.path.isdir("./result"): os.makedirs("./result") print colored(color("[+] Creating [./result] directory for resulting code files","green")) os.system(raw_payload) try: with open(shellcodeFile) as shellcodeFileHandle: shellcodeBytes = bytearray(shellcodeFileHandle.read()) shellcodeFileHandle.close() print (color("[*] Shellcode file [{}] successfully loaded".format(shellcodeFile))) except IOError: print (color("[!] Could not open or read file [{}]".format(shellcodeFile))) quit() print (color("[*] MD5 hash of the initial shellcode: [{}]".format(MD5.new(shellcodeBytes).hexdigest()))) print (color("[*] Shellcode size: [{}] bytes".format(len(shellcodeBytes)))) masterKey = raw_input(color(' [?] Enter the Key to Encrypt Shellcode with : ')) print (color("[+] XOR Encrypting the shellcode with key [{}]".format(masterKey))) transformedShellcode = xor(shellcodeBytes, masterKey) cipherType = 'xor' print color(("[*] Encrypted shellcode size: [{}] bytes".format(len(transformedShellcode)))) # Writing To File print color("[*] Generating C code file") writetofile(transformedShellcode, masterKey, cipherType,lport)
def md5hex(data): h = MD5.new() h.update(data) return b2a_hex(h.digest())
def bytestolow(data): h = MD5.new() h.update(data) shash = h.digest() return hexlify(shash).lower()[0:16]
async def hash_MD5(data) -> str: if isinstance(data, str): hash_digest = MD5.new(data=str.encode(data)) else: hash_digest = MD5.new(data=data) return hash_digest.hexdigest()
def check_md5_sum(): f = open('test_file') hashsum = MD5.new() hashsum.update(f.read()) self.assertEqual(hashsum.hexdigest(), "215b177db8eed86d028b37e5cbad55c7")