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 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 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 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 _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 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 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 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 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 _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 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 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 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 __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 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 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 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 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 _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 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 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 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 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 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 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 __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 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 sn_getenckey(dummy=None): txt,ok = QInputDialog.getText(None, 'Enter key', 'Enter key.\nData lost if key is lost.\nSee docs. for key upgrade notes.', ) if not ok: return if str(txt).startswith('v0:'): txt = QString(txt[3:]) else: txt = g.toUnicode(txt) # arbitrary kludge to convert string to 256 bits - don't change sha = SHA.new() md5 = MD5.new() sha.update(txt.encode('utf-8')) md5.update(txt.encode('utf-8')) __ENCKEY[0] = sha.digest()[:16] + md5.digest()[:16] if len(__ENCKEY[0]) != 32: raise Exception("sn_getenckey failed to build key")
def contains(self, key): a = MD5.new() a.update(key.encode("utf-8")) key = int(a.hexdigest(),16) index = key % self.capacity n = self.data[index] if self.data[index]==None: return False else: node=self.data[index] while node is not None: if node.val == key: return True else: node=node.next return False
def contains(self, key): number = int(MD5.new(key.encode("utf-8")).hexdigest(), 16) index = number % self.capacity blank = self.data[index] if blank == None: return False else: while blank: if blank.val == number: return True elif blank.val != number: blank = blank.next if blank == None: return False
def add(self,key): a = MD5.new() a.update(key.encode("utf-8")) key = int(a.hexdigest(),16) index = key % self.capacity n = self.data[index] if self.data[index] == None: self.data[index] = ListNode(key) else: while n.next is not None: n = n.next n.next = ListNode(key)
def remove(self, key): h = MD5.new() h.update(key.encode("UTF-8")) x = int(h.hexdigest(), 16) k = x % self.capacity target = self.data[k] while target: if target.val == x: self.data[k] = target.next return else: previous = None while target: if target.val == x: previous.next = target.next return else: previous = target target = target.next
def after_auth(self, data, auth_key): """ Key change after the authentification was successful. Parameters ---------- auth_key AES authentification key used to calculate the challenge (From password of the user) data Data from the request """ self.encryption.aes_key = auth_key if not self.cookies: self.cookies = self.last_response.cookies work = self.encryption.aes_decrypt( bytes.fromhex(data['donneesSec']['donnees']['cle'])) key = MD5.new(_enBytes(work.decode())) key = key.digest() self.encryption.aes_key = key
def remove(self, key): h = MD5.new() h.update(key.encode(encoding='utf-8')) x = h.hexdigest x = int(h.hexdigest(), 16) index = x % self.capacity cn = self.data[index] pre = None while cn is not None: if cn.val == x: if pre is None: self.data[index] = cn.next else: pre.next = cn.next break else: pre = cn cur = cn.next
def GeneratePayload(mac, username, password=""): # Pad the input correctly assert (len(mac) < 0x10) just_mac = mac.ljust(0x10, "\x00") assert (len(username) <= 0x10) just_username = username.ljust(0x10, "\x00") assert (len(password) <= 0x10) just_password = password.ljust(0x10, "\x00") cleartext = (just_mac + just_username + just_password).ljust(0x70, '\x00') md5_key = MD5.new(cleartext).digest() payload = ByteSwap((md5_key + cleartext).ljust(0x80, "\x00")) secret_key = "AMBIT_TELNET_ENABLE+" + password return ByteSwap(Blowfish.new(secret_key, 1).encrypt(payload))
def checkKDCAuthority(message, randomT): signer = PKCS1_v1_5.new(authorityPublicKey) #Package encryptPackage = message[512: len(message)] #signal #Because we adding zero byte to match the length of header, we should get the part actually be signaturePart = "" for i in range(512): if message[i] != '\000': signaturePart += message[i] h = MD5.new() h.update(encryptPackage) if not signer.verify(h, signaturePart): print "Signature Fail" return False else: package = message[512: len(message)] random = package.split('||')[0] return random == randomT
def encrypt(payload: dict, devicekey: str): devicekey = devicekey.encode('utf-8') hash_ = MD5.new() hash_.update(devicekey) key = hash_.digest() iv = get_random_bytes(16) plaintext = json.dumps(payload['data']).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC, iv=iv) padded = pad(plaintext, AES.block_size) ciphertext = cipher.encrypt(padded) payload['encrypt'] = True payload['iv'] = b64encode(iv).decode('utf-8') payload['data'] = b64encode(ciphertext).decode('utf-8') return payload
def md5(obj, ret_hex=True): """ Run md5: If content is a list, it will update multiple times in items. Or it will return md5(content). :param obj: list/byte/str If it's a list, it will update multiple times in items. :param ret_hex: return hexdigest, or it will return a md5 obj :return: str/md5 md5 result """ md5_ = MD5.new() if isinstance(obj, list): for item in obj: md5_.update(to_byte(item)) elif len(to_byte(obj)) > 500: return Cryptor.md5(cut_bytes(to_byte(obj), cut_length=500), ret_hex=ret_hex) else: md5_.update(to_byte(obj)) return md5_.hexdigest() if ret_hex else md5_
def updata_file(self, strs, nass_name='文件'): obj = MD5.new() obj.update(robot_secret.encode("utf-8")) # gb2312 Or utf-8 robotPwd = obj.hexdigest() # 十六进制加密 url = f'{base_url}/file/upload/{serial_no}/{robotPwd}' header = { # "content-type": "application/json" } try: data = {} files = {'file': open(strs, 'rb')} r = requests.post(url=url, headers=header, files=files) ret = r.json().get('data') url = ret.get('url').replace('文件下载', nass_name) path = ret.get('path') logger.success(url, filename=path) except Exception as e: print(e)
def _encrypt_message(self, data: dict) -> dict: iv = get_random_bytes(16) data['iv'] = b64encode(iv).decode("utf-8") api_key = bytes(self._device.api_key, 'utf-8') plaintext = bytes(data['data'], 'utf-8') hash = MD5.new() hash.update(api_key) key = hash.digest() cipher = AES.new(key, AES.MODE_CBC, iv=iv) padded = pad(plaintext, AES.block_size) ciphertext = cipher.encrypt(padded) encoded = b64encode(ciphertext) data['data'] = encoded.decode("utf-8") return data
def contains(self, key): h = MD5.new() h.update(key.encode('utf-8')) key = int(h.hexdigest(), 16) index = key % self.capacity ptr = self.data[index] try: while (ptr.val != key): ptr = ptr.next except: pass if ptr == None: return False elif ptr.val == key: return True
def SSLv3PRF(masterKey, RaSeed, RbSeed, requestedLength): alphaBytes = [ b"A", b"B", b"C", b"D", b"E", b"F", b"G", b"H", b"I", b"J", b"K", b"L", b"M", b"N", b"O", b"P", b"Q", b"R", b"S", b"T", b"U", b"V", b"W", b"X", b"Y", b"Z" ] finalResult = b"" hashLength = 16 rounds = requestedLength + (hashLength - 1) for i in range(rounds): letters = alphaBytes[i % 26] * (i + 1) sha1Digest = SHA1.new(letters + masterKey + RaSeed + RbSeed).digest() finalResult += MD5.new(masterKey + sha1Digest).digest() return finalResult[:requestedLength]
def cycle_arduino_to_pc(arduino): arduino_encryted_hash = [] arduino.readline() arduino.readline() for i in range(16): arduino_encryted_hash.append(int(arduino.readline())) print "arduino_encryted_hash = ", arduino_encryted_hash arduino_msg_length = int(arduino.readline()) arduino_msg = '' for i in range(arduino_msg_length): arduino_msg += arduino.readline()[0] print "msg =", arduino_msg msg_hash_by_pc = MD5.new(arduino_msg) msg_hash_by_pc_string = msg_hash_by_pc.digest() print "msg_hash_by_pc_string = ", msg_hash_by_pc_string msg_hash_by_pc_int_list = [] for i in range(len(msg_hash_by_pc_string)): msg_hash_by_pc_int_list.append(ord(msg_hash_by_pc_string[i])) print "msg_hash_by_pc_int_list = ", msg_hash_by_pc_int_list plain_hash = RSA.rsa_decrypt(arduino_encryted_hash, RSA_Others_Public_Key) hash_int_list = [] for val in plain_hash: hash_int_list.append(ord(val)) print "hash_int_list = ", hash_int_list if hash_int_list == msg_hash_by_pc_int_list: print "Hash and Message match!" else: print "Hash and Message do not match!"
def parse_args(self,args=None,values=None, passphrase=None,prompt='Enter the pass phrase: '): """ Parses command line arguments """ # do the normal parsing (options,args) = optparse.OptionParser.parse_args(self,args,values) # build a table summarizing all non-secret options table = [ ] for opt in self.option_list: if opt.dest and opt.dest not in self.secretOptions: value = getattr(options,opt.dest) if opt.default == optparse.NO_DEFAULT: default_value = '(none)' else: default_value = opt.default table.append((str(opt),value,default_value,opt.help)) # add the summary table to the returned options options._summary_table = table # is there is any secret data that needs decrypting? if self.secretOptions: import getpass # only introduce these external dependencies if necessary try: from Crypto.Hash import MD5 as hasher from Crypto.Cipher import AES as cipher except ImportError: raise ImportError('secret options require the Crypto package') if not passphrase: passphrase = getpass.getpass(prompt) key = hasher.new(passphrase).digest() assert(len(key) in [16,24,32]) engine = cipher.new(key,cipher.MODE_ECB) for secret in self.secretOptions: data = engine.decrypt(ConfigOptionParser.hex2bin(getattr(options,secret))) npad = ord(data[-1]) if (npad <= 0 or npad > cipher.block_size or data[-npad:-1] != '\x00'*(npad-1)): raise optparse.OptionValueError('badly formed value for %s' % secret) setattr(options,secret,data[0:-npad]) # return the parse results return (options,args)
def key_packet_fingerprint(packet): if packet.version < 4: md5 = MD5.new() # Key type must be RSA for v2 and v3 public keys if packet.public_key_algorithm in (1, 2, 3): md5.update(int_to_bytes(packet.modulus_n)) md5.update(int_to_bytes(packet.exponent_e)) elif packet.public_key_algorithm in (16, 20): md5.update(int_to_bytes(packet.prime_p)) md5.update(int_to_bytes(packet.group_generator_g)) fingerprint = md5.hexdigest().upper() elif packet.version >= 4: sha1 = SHA.new() pubkey_data = packet.public_content pubkey_length = len(pubkey_data) seed_bytes = (0x99, (pubkey_length >> 8) & 0xff, pubkey_length & 0xff) sha1.update(bytearray(seed_bytes)) sha1.update(pubkey_data) fingerprint = sha1.hexdigest().upper() return fingerprint
def add(self, key): h = MD5.new() h.update(key.encode(encoding='utf-8')) x = h.hexdigest x = int(h.hexdigest(), 16) index = x % self.capacity if self.data[index] == None: self.data[index] = ListNode(x) else: cn = self.data[index] if cn: while cn.next: if cn.next.val == x: return else: cn = cn.next cn.next = ListNode(x)
def decrypt(payload: dict, devicekey: str): try: devicekey = devicekey.encode('utf-8') hash_ = MD5.new() hash_.update(devicekey) key = hash_.digest() encoded = ''.join([ payload[f'data{i}'] for i in range(1, 4, 1) if f'data{i}' in payload ]) cipher = AES.new(key, AES.MODE_CBC, iv=b64decode(payload['iv'])) ciphertext = b64decode(encoded) padded = cipher.decrypt(ciphertext) return unpad(padded, AES.block_size) except: return None
def remove(self, key): h = MD5.new() h.update(key.encode("utf-8")) x = h.hexdigest() key = int(h.hexdigest(),16) index = key % self.capacity node = self.data[index] if node!= None and node.val == key: self.data[index] = node.next return pre_node = None while node.next: if node.next == key: pre_node.next = node.next return pre_node = node node.next = node.next.next return
def secretCheck(parsePacket): # maybe use secret query first secret = SecretQuery((parsePacket['src'])[0]) headers = b'' for key, value in parsePacket.items(): if (key != 'HMAC'): # take packet except hmac headers = headers + value Hash = parsePacket['HMAC'].hex() # get bytes literally temp = headers + secret.encode() ht = MD5.new() ht.update(temp) final = ht.hexdigest() print("HASH COMPUTED: ", final) print("HASH RECEIVED: ", Hash) if Hash == final: print("Packet is valid") sqliteConnector.updateTimer(parsePacket['src'][0], 1) return True else: print("Packet is invalid") return False
def get_path_hash(path_str, md5_hash=False): dirname = os.path.dirname(path_str) basename = os.path.basename(path_str) # if md5_hash: h = MD5.new() else: h = hashlib.sha256() if sys.version_info[0] > 2: # Python3 h.update(basename.encode("utf-8")) else: # Python2 h.update(basename) if dirname != '/': return "%s/.%s" % (dirname, h.hexdigest()) else: return "/.%s" % h.hexdigest()
def generateChecksum(hash, filename): h = None if hash == MD5: h = MD5.new() elif hash == SHA256: h = SHA256.new() elif hash == SHA: h = SHA.new() else: # None support return None with open(filename) as f: while True: block = f.read(BLOCK_SIZE) if len(block) == 0: break h.update(block) return h.hexdigest()
def decrypt(self, data_element, iv): try: api_key = bytes(self.api_key, 'utf-8') encoded = data_element hash = MD5.new() hash.update(api_key) key = hash.digest() cipher = AES.new(key, AES.MODE_CBC, iv=b64decode(iv)) ciphertext = b64decode(encoded) padded = cipher.decrypt(ciphertext) plaintext = unpad(padded, AES.block_size) except Exception as ex: self.logger.error('Error decrypting for device %s: %s, probably wrong API key', self.device_id, format(ex)) return plaintext
def add_user(censusid, password, user_type, name): #CHECK salt = ''.join(choice(ascii_uppercase) for i in range(12)) salted_password = password + str(salt) hashed_password = MD5.new(salted_password.encode()).hexdigest() register = False # If censusID not in database then fail if database.check_user_exists(censusid) == False: err_str = "ID not found. Ask a staff member to check your enrollment" return err_str, register r = requests.post("{target}/waf/password/{txt}".format(target=waf_str, txt=password)) if r.text != "True": return r.text, register if database.get_user(censusid)['password'] != "": err_str = "User has already been registered" return err_str, register database.add_user(censusid, hashed_password, user_type, name, salt) register_string = "Success!" register = True return register_string, register
def remove(self, key): h = MD5.new() h.update(key.encode("utf-8")) x = int(h.hexdigest(), 16) y = x % self.capacity z = self.data[y] if self.contains(key) != True: return else: if z.val == x: self.data[y] = self.data[y].next return else: point = self.data[y] while point.next.val != x: point = point.next point.next = point.next.next
def md5(self): """Get MD5 hash MD5 (Message-Digest 5) is a widely used hash function. It has been used in a variety of security applications and is also commonly used to check the integrity of files.<br><br>However, MD5 is not collision resistant and it isn't suitable for applications like SSL/TLS certificates or digital signatures that rely on this property. Returns: Chepy: The Chepy object. Examples: >>> Chepy("A").md5().output "7fc56270e7a70fa81a5935b72eacbe29" """ h = MD5.new() h.update(self._convert_to_bytes()) self.state = h.hexdigest() return self
def HMACCheck(parsePacket): print("HMAC CHECK") headers = b'' for key, value in parsePacket.items(): if (key != 'HMAC'): # take packet except hmac headers = headers + value Hash = parsePacket['HMAC'].hex() # get bytes literally temp = headers + secret.encode() ht = MD5.new() ht.update(temp) final = ht.hexdigest() print("HASH COMPUTED: ",final) print("HASH RECEIVED: ", Hash) #If computed hash is same with received hash, it has passsed authentication if Hash == final: print("Packet is valid") return True #Else, it has not passed authentication else: print("Packet is invalid") return False
def remove(self, name): h = MD5.new() h.update(name.encode("utf-8")) key = int(h.hexdigest(), 16) while self.contains(name): n = key % self.capacity node = self.data[n] before = None if node is None: print(False) return elif node.val == key: self.data[n] = node.next else: before = None while node: if node.val == key: before.next = node.next return before = node node = node.next