def level1(): if request.method == 'POST': username = request.form['username'] cipher = ARC4.new(KEY) token = cipher.encrypt(TOKEN.format(username).encode()) return redirect(url_for('stream_ciphers_level1', token=raw_to_hex(token))) elif request.method == 'GET': cpt = request.args.get('token', None) if cpt is None: return render_template('single_input.html', title='RC4 token', msg='Please sign up:', action=url_for('stream_ciphers_level1'), input_msg='Username', input='username') else: cipher = ARC4.new(KEY) msg = cipher.decrypt(hex_to_raw(cpt)).decode() d = {parameter.split('=')[0]:parameter.split('=')[1] for parameter in msg.split('&')} flag = FLAG1 if d['admin'] == '1' else '' return render_template('generic.html', title='RC4 token', msg="Hello {}!".format(d['username']), flag=flag, flag_error="Only admins can see the flag, but you're not an admin are you? (admin=0)")
def cipherChange(self, algorithm, pw="awesomekey"): if algorithm == self.cipher: return elif algorithm == "ARC4-1": self.key = "murphy" self.cipher = "ARC4" self.cipher_inp = ARC4.new(self.key) self.cipher_outp = ARC4.new(self.key) cc = "cipherchange:cipher=ARC4:keylen=%d:charset=alpha" % (len(self.key)) elif algorithm == "ARC4-2": self.key = pw self.cipher = "ARC4" self.cipher_inp = ARC4.new(self.key) self.cipher_outp = ARC4.new(self.key) cc = "cipherchange:cipher=ARC4:keylen=%d:charset=alpha" % (len(self.key)) elif algorithm == "XOR": self.cipher = "XOR" cc = "cipherchange:cipher=XOR:keylen=128" elif algorithm == "NONE": self.cipher = "NONE" cc = "cipherchange:cipher=NONE:keylen=0" else: raise CryptoError("Cipher %s unknown" % (algorithm)) print "%s/NONE> %s" % (self.ip, cc) sys.stdout.flush() self.writeClear(cc + "\r\n")
def open_encrypted_socket(addr, port, key="secret"): fd1, fd2 = socket.socketpair() pid = os.fork() if pid == 0: fd1.close() enc_rc4 = ARC4.new(key) dec_rc4 = ARC4.new(key) sock = socket.socket() sock.connect((addr, port)) while True: r,w,x = select.select([sock, fd2], [], []) if sock in r: data = sock.recv(1024) if data == "": break; data = dec_rc4.decrypt(data) fd2.send(data) if fd2 in r: data = fd2.recv(1024) if data == "": break; data = enc_rc4.encrypt(data) sock.send(data) sock.close() fd2.close() exit(0) if pid > 0: fd2.close() s = pwn.sock.sock("default") s.sock = fd1 s.settimeout("default") return s fd1.close() fd2.close() return None
def test_NetrLogonSamLogonEx(self): dce, rpctransport = self.connect() request = nrpc.NetrLogonSamLogonEx() request['LogonServer'] = '\x00' request['ComputerName'] = self.serverName + '\x00' request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation request['LogonInformation']['LogonInteractive']['Identity']['LogonDomainName'] = self.domain request['LogonInformation']['LogonInteractive']['Identity']['ParameterControl'] = 2 + 2**14 + 2**7 + 2**9 + 2**5 + 2**11 request['LogonInformation']['LogonInteractive']['Identity']['UserName'] = self.username request['LogonInformation']['LogonInteractive']['Identity']['Workstation'] = '' if len(self.hashes) > 0: lmhash, nthash = self.hashes.split(':') lmhash = unhexlify(lmhash) nthash = unhexlify(nthash) else: lmhash = ntlm.LMOWFv1(self.password) nthash = ntlm.NTOWFv1(self.password) try: from Crypto.Cipher import ARC4 except Exception: print "Warning: You don't have any crypto installed. You need PyCrypto" print "See http://www.pycrypto.org/" rc4 = ARC4.new(self.sessionKey) lmhash = rc4.encrypt(lmhash) rc4 = ARC4.new(self.sessionKey) nthash = rc4.encrypt(nthash) request['LogonInformation']['LogonInteractive']['LmOwfPassword'] = lmhash request['LogonInformation']['LogonInteractive']['NtOwfPassword'] = nthash request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4 request['ExtraFlags'] = 1 resp = dce.request(request) resp.dump()
def default(self, line): if line.startswith('*'): line = line[1:] command = (line.strip('\n')+'\x00').encode('utf-16le') command = ARC4.new(self.key).encrypt(command) resp = mimilib.hMimiCommand(self.dce, self.pHandle, command) cipherText = ''.join(resp['encResult']) cipher = ARC4.new(self.key) print cipher.decrypt(cipherText)
def auth(req): req.cookies = [] req.user = None qonvo_auth = None qonvo_uid = None auth_cookie = None cookies = req.headers.getHeader('cookie', []) if cookies: for cookie in cookies: if cookie.name == 'qonvo_auth': qonvo_auth = cookie.value elif cookie.name == 'qonvo_id': qonvo_uid = cookie.value elif cookie.name == 'auth': try: data = StringIO(ARC4.new(SECRET_KEY).decrypt(cookie.value.decode('base64'))) row = cPickle.load(data) user = User(row) data.close() if row['ip'] == req.remoteAddr.host: req.user = user except: pass if getattr(req.user, 'id', None) != qonvo_uid: req.user = None auth_cookie = Cookie('auth','',path='/') elif req.user: return None if qonvo_auth and qonvo_uid: validated = validate(qonvo_auth, qonvo_uid) if validated: validated['ip'] = req.remoteAddr.host dump = StringIO() cPickle.dump(validated, dump) data = dump.getvalue() dump.close() auth = ''.join(ARC4.new(SECRET_KEY).encrypt(data).encode('base64').splitlines()).strip() auth_cookie = Cookie('auth',auth,path='/') req.user = User(validated) if auth_cookie: req.cookies.append(auth_cookie) return None
def set_skey(self, SKEY): if not self.block3b: self.block3b = self._gen_block3b(SKEY) crypta = ARC4.new(hashlib.sha1(b'keyA' + self.S + SKEY).digest()) cryptb = ARC4.new(hashlib.sha1(b'keyB' + self.S + SKEY).digest()) if self.initiator: self.encrypt = crypta.encrypt self.decrypt = cryptb.decrypt else: self.encrypt = cryptb.encrypt self.decrypt = crypta.decrypt self.encrypt(b'x' * 1024) # discard first 1024 bytes self.decrypt(b'x' * 1024)
def set_skey(self, SKEY): if not self.block3b: self.block3b = self._gen_block3b(SKEY) crypta = ARC4.new(sha("keyA" + self.S + SKEY).digest()) cryptb = ARC4.new(sha("keyB" + self.S + SKEY).digest()) if self.initiator: self.encrypt = crypta.encrypt self.decrypt = cryptb.decrypt else: self.encrypt = cryptb.encrypt self.decrypt = crypta.decrypt self.encrypt("x" * 1024) # discard first 1024 bytes self.decrypt("x" * 1024)
def compute_u(self, key): if self.r == 2: # Algorithm 3.4 return ARC4.new(key).encrypt(self.PASSWORD_PADDING) # 2 else: # Algorithm 3.5 hash = md5.md5(self.PASSWORD_PADDING) # 2 hash.update(self.docid[0]) # 3 result = ARC4.new(key).encrypt(hash.digest()) # 4 for i in range(1, 20): # 5 k = b"".join(six.int2byte(c ^ i) for c in six.iterbytes(key)) result = ARC4.new(k).encrypt(result) result += result # 6 return result
def compute_u(self, key): if self.r == 2: # Algorithm 3.4 return ARC4.new(key).encrypt(self.PASSWORD_PADDING) # 2 else: # Algorithm 3.5 hash = md5.md5(self.PASSWORD_PADDING) # 2 hash.update(self.docid[0]) # 3 result = ARC4.new(key).encrypt(hash.digest()) # 4 for i in range(1, 20): # 5 k = ''.join(chr(ord(c) ^ i) for c in key) result = ARC4.new(k).encrypt(result) result += result # 6 return result
def init(self, sock): from Crypto.Cipher import ARC4 txnonce = s_common.guid() sock.sendall(txnonce) rxnonce = sock.recvall(16) if rxnonce == None: return txkey = hashlib.sha256( txnonce + self.rc4key ).digest() rxkey = hashlib.sha256( rxnonce + self.rc4key ).digest() self.txcrypt = ARC4.new( txkey ) self.rxcrypt = ARC4.new( rxkey )
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 __getPek(self): logging.info('Searching for pekList, be patient') peklist = None while True: record = self.__ESEDB.getNextRow(self.__cursor) if record is None: break elif record[self.NAME_TO_INTERNAL['pekList']] is not None: peklist = unhexlify(record[self.NAME_TO_INTERNAL['pekList']]) break elif record[self.NAME_TO_INTERNAL['sAMAccountType']] in self.ACCOUNT_TYPES: # Okey.. we found some users, but we're not yet ready to process them. # Let's just store them in a temp list self.__tmpUsers.append(record) if peklist is not None: encryptedPekList = self.PEKLIST_ENC(peklist) md5 = hashlib.new('md5') md5.update(self.__bootKey) for i in range(1000): md5.update(encryptedPekList['KeyMaterial']) tmpKey = md5.digest() rc4 = ARC4.new(tmpKey) decryptedPekList = self.PEKLIST_PLAIN(rc4.encrypt(encryptedPekList['EncryptedPek'])) PEKLen = len(self.PEK_KEY()) for i in range(len( decryptedPekList['DecryptedPek'] ) / PEKLen ): cursor = i * PEKLen pek = self.PEK_KEY(decryptedPekList['DecryptedPek'][cursor:cursor+PEKLen]) logging.info("PEK # %d found and decrypted: %s", i, hexlify(pek['Key'])) self.__PEK.append(pek['Key'])
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 copy(self, src, dest): keyobj = cipher.new(self.key) inF = open(src, 'rb') oF = open(dest, 'wb') oF.write(keyobj.decrypt(inF.read())) inF.close() oF.close()
def getrc4encodehex(mapdata): tempkey = '123465' cipher = ARC4.new(tempkey) jsonstr = json.dumps(mapdata) msg = cipher.encrypt(jsonstr) hexstr = binascii.b2a_hex(msg[:]) return hexstr
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 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 getrc4encodebase64(mapdata): tempkey = '123465' cipher = ARC4.new(tempkey) jsonstr = json.dumps(mapdata) msg = cipher.encrypt(jsonstr) base64str = base64.b64encode(msg) return base64str
def clean_magic(self): m = self.cleaned_data["magic"] arc4 = ARC4.new(settings.SECRET_KEY) try: plain = arc4.decrypt(b64decode(str(m))) data = pickle.loads(plain) before = data["curtime"] remote_ip = data["remote_ip"] unique_id = data["unique_id"] except (TypeError, pickle.UnpicklingError, KeyError): raise forms.ValidationError(_("Invalid security token")) if remote_ip != self.remote_ip or unique_id != self.unique_id: raise forms.ValidationError(_("Invalid security token")) try: curdelta = datetime.now() - before except TypeError: raise forms.ValidationError(_("Invalid security token")) mindelta = timedelta(seconds=MIN_WAIT_SECONDS) if curdelta < mindelta: d = mindelta - curdelta raise forms.ValidationError( _("Wait for another %.2f seconds before submitting this form") % (d.seconds + float(d.microseconds) / 1000000) ) if curdelta > timedelta(seconds=MAX_WAIT_SECONDS): raise forms.ValidationError(_("This form has expired. Reload the page to get a new one")) return m
def handle_message(self, message): if message.opcode == 0x1ED: # CMSG_AUTH_SESSION # After a CMSG_AUTH_SESSION packet, all traffic is encrypted. self.encrypted = True # Fortunately, the auth session packet contains the account name, which allows us to identify # the session that is associated with this connection. account = unicode(readstring(message.data, 8), "utf8") if self.sniffer and account in self.sniffer.sessions: # We check whether we have recorded a session for this account name. self.session = self.sniffer.sessions[account] if self.session.key: # If we have a key, setup encryption. for peer in (self.client, self.server): self.rc4[peer] = ARC4.new(hmac.new(peer.hmac_key, self.session.key, sha1).digest()) # To prevent leaking key bytes, Blizzard encrypts a few null bytes before encrypting # anything that is sent over the network. self.rc4[peer].decrypt(chr(0) * 1024) if self.sniffer: # Dispatch the message to our sniffer's message handler. stream.fire(opcodes.names[message.opcode], message) self.sniffer.message_handler(message)
def get_user_info(username): q = "SELECT realname, pubkey, gender FROM users WHERE username = ?" realname, pubkey, gender = query_db(q, [username], one=True) q = "SELECT user2 FROM friends WHERE user1 = ?" res = query_db(q, [username]) friends = [friend[0] for friend in res] q = "SELECT sender, content FROM messages WHERE receiver=?" messages = query_db(q, [username]) if not session.get("locked") and username == session.get("user"): password = session.get("password") tmp = [] for (user, message) in messages: content_enc = b64decode(message) q = "SELECT privkeyenc FROM users WHERE username = ?" res = query_db(q, [username], one=True)[0] priv_receiver = ARC4.new(password).decrypt(b64decode(res)) key = RSA.importKey(priv_receiver) message = key.decrypt(content_enc).decode("utf-8") tmp.append((user, message)) messages = tmp info = {"realname":realname, "pubkey":pubkey, "friends":friends, "gender":gender, "messages":messages} return info
def init_crypto_nt5(self): rc4_key_len = self.get_constant_object( 'g_cbRandomKey', 'unsigned long').v() rc4_key_ptr = self.get_constant_object( 'g_pRandomKey', target='Pointer') self.rc4_key = rc4_key_ptr.dereference_as( 'String', target_args=dict(length=rc4_key_len, term=None)).v() desx_key_ptr = self.get_constant_object( 'g_pDESXKey', target='Pointer') self.desx_key = desx_key_ptr.dereference_as( 'String', target_args=dict(length=144, term=None)).v() self.feedback = self.get_constant_object( 'g_Feedback', target='String', target_args=dict(length=8)).v() try: cipher = ARC4.new(self.rc4_key) decryption_enabled = True except ValueError as e_ve: decryption_enabled = False logging.warning('init_crypto_nt5 exception {}'.format(e_ve)) finally: return decryption_enabled
def do_GET(self): """Sends commands b64 encoded in HTTP responses """ global last_command, output_ready,command_ready,password, salt if ((self.client_address[0] == socket.gethostbyname(host)) and command_ready): self.send_response(200) # begin sending response if encrypt: salt = self.headers["Content-Salt"].strip() # extract the salt the client is using if verbose: print "received salt from client: "+salt hasher = SHA.new() # new hasher hasher.update(password + salt) # create the hash of the string passwordsalt rc4 = ARC4.new(hasher.hexdigest()) # use the hash for password to avoid weak key scheduling self.end_headers() # end of response headers self.wfile.write(base64.b64encode(rc4.encrypt(last_command))) # send payload else: # send payload without encryption self.end_headers() self.wfile.write(base64.b64encode(last_command)) command_ready=False # wait for next command else: # GET does not come from the client we are currently listening to or there is no command available yet self.send_response(200) # send empty response and end self.send_header("Content-Type","0") # no command issued self.end_headers() # Check special header to know client current polling period if "Next-Polling-In" in self.headers: global next_polling,timestamp,client_sync next_polling = self.headers["Next-Polling-In"] # so the server can calculate roughly next polling # set the time of last request timestamp = int(time.time()) client_sync = True
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 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 __decryptHash(self, key, value, iv): hmac_md5 = HMAC.new(key,iv) rc4key = hmac_md5.digest() rc4 = ARC4.new(rc4key) data = rc4.encrypt(value) return data
def get_cipher(): from Crypto.Cipher import ARC4 if hasattr( settings, 'CAMELOT_DBPROFILES_CIPHER' ): key = getattr( settings, 'CAMELOT_DBPROFILES_CIPHER' ) else: key = 'The Knights Who Say Ni' return ARC4.new( key )
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 craftFinishedRecord(keys, hs, seq, ciphersuite): clientfinished = craftFinished(keys, hs) record_cf = craftSSLRecord("\x16", clientfinished) hs.md5.update(clientfinished) hs.sha1.update(clientfinished) # Calculate MAC seqnumber = struct.pack('!Q', seq.client) # First record seq number is zero seq.client += 1 recordmac = hmac.HMAC(keys.client_write_MAC_secret, seqnumber+record_cf, hashlib.sha1).digest() if ciphersuite == CIPHER_AES128_SHA or ciphersuite == CIPHER_DHE_RSA_AES128_SHA: # Encrypt(finished message + HMAC + padding) tobeencrypted = clientfinished + recordmac + "\x0b"*12 aescipher = AES.new(keys.client_write_key, AES.MODE_CBC, keys.client_write_IV) cipherfinished = aescipher.encrypt(tobeencrypted) keys.client_write_IV = cipherfinished[-16:] elif ciphersuite == CIPHER_RC4_SHA: # Encrypt(finished message + HMAC ) tobeencrypted = clientfinished + recordmac keys.client_rc4 = ARC4.new(keys.client_write_key) cipherfinished = keys.client_rc4.encrypt(tobeencrypted) record_finished = craftSSLRecord("\x16", cipherfinished) return record_finished
def get_tx_info (tx, block_index): """ The destinations, if they exist, always comes before the data output; the change, if it exists, always comes after. """ # Fee is the input values minus output values. fee = 0 # Get destination outputs and data output. destinations, btc_amount, data = [], None, b'' pubkeyhash_encoding = False for vout in tx['vout']: fee -= vout['value'] * config.UNIT # Sum data chunks to get data. (Can mix OP_RETURN and multi-sig.) asm = vout['scriptPubKey']['asm'].split(' ') if len(asm) == 2 and asm[0] == 'OP_RETURN': # OP_RETURN try: data_chunk = binascii.unhexlify(bytes(asm[1], 'utf-8')) except binascii.Error: continue data += data_chunk elif len(asm) == 5 and asm[0] == '1' and asm[3] == '2' and asm[4] == 'OP_CHECKMULTISIG': # Multi-sig try: data_pubkey = binascii.unhexlify(bytes(asm[2], 'utf-8')) except binascii.Error: continue data_chunk_length = data_pubkey[0] # No ord() necessary. data_chunk = data_pubkey[1:data_chunk_length + 1] data += data_chunk elif len(asm) == 5 and (block_index >= 293000 or config.TESTNET): # Protocol change. # Be strict. pubkeyhash_string = get_pubkeyhash(vout['scriptPubKey']) try: pubkeyhash = binascii.unhexlify(bytes(pubkeyhash_string, 'utf-8')) except binascii.Error: continue if 'coinbase' in tx['vin'][0]: return b'', None, None, None, None obj1 = ARC4.new(binascii.unhexlify(bytes(tx['vin'][0]['txid'], 'utf-8'))) data_pubkey = obj1.decrypt(pubkeyhash) if data_pubkey[1:9] == config.PREFIX or pubkeyhash_encoding: pubkeyhash_encoding = True data_chunk_length = data_pubkey[0] # No ord() necessary. data_chunk = data_pubkey[1:data_chunk_length + 1] if data_chunk[-8:] == config.PREFIX: data += data_chunk[:-8] break else: data += data_chunk # Destinations are outputs before the data. if not data: address = get_address(vout['scriptPubKey']) if address: destinations.append(address) btc_amount = round(vout['value'] * config.UNIT) # Floats are awful. # Check for, and strip away, prefix (except for burns). if destinations == [config.UNSPENDABLE,]: pass elif data[:len(config.PREFIX)] == config.PREFIX: data = data[len(config.PREFIX):] else: return b'', None, None, None, None # Only look for source if data were found or destination is UNSPENDABLE, for speed. if not data and destinations != [config.UNSPENDABLE,]: return b'', None, None, None, None # Collect all possible source addresses; ignore coinbase transactions and anything but the simplest Pay‐to‐PubkeyHash inputs. source_list = [] for vin in tx['vin']: # Loop through input transactions. if 'coinbase' in vin: return b'', None, None, None, None vin_tx = bitcoin.get_raw_transaction(vin['txid']) # Get the full transaction data for this input transaction. vout = vin_tx['vout'][vin['vout']] fee += vout['value'] * config.UNIT address = get_address(vout['scriptPubKey']) if not address: return b'', None, None, None, None else: source_list.append(address) # Require that all possible source addresses be the same. if all(x == source_list[0] for x in source_list): source = source_list[0] else: source = None return source, destinations, btc_amount, round(fee), data
def test_drop256_decrypt(self): cipher_drop = ARC4.new(self.key, 256) pt_drop = cipher_drop.decrypt(self.data[:16]) pt = self.cipher.decrypt(self.data)[256:256+16] self.assertEquals(pt_drop, pt)
def decrypt_CG(self, cf): secret = cf.key key = hmac.new(secret, CG[0x10:0x20], sha).digest()[0:0x10] cg = self.data[:0x10] + key + RC4.new(key).decrypt(self.data[0x20:]) self.data = cg
message = message.decode() print(server_name, ">", message) message = input(str("Me > ")) if message[0] == '!': if message[1:] == "bye": soc.send(message.encode()) print("\n") break else: arg = message.split(' ') delta = time.time() timer = True if arg[0] == '!rc4': input_file = open(arg[1], 'rb') input_data = input_file.read() cfb_cipher = ARC4.new(arg[2]) message = '!rc4'+str(cfb_cipher.encrypt(input_data)) with open('key.txt', 'w') as f: f.write(arg[2]) elif arg[0] == '!des': input_file = open(arg[1], 'rb') input_data = input_file.read() while len(input_data) % 8 != 0: input_data += bytes('@', 'utf-8') cfb_cipher = DES.new(arg[2]) with open('key.txt', 'w') as f: f.write(arg[2]) message = '!des'+str(cfb_cipher.encrypt(input_data)) elif arg[0] == '!aes': input_file = open(arg[1], 'rb')
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 test_drop256_encrypt(self): cipher_drop = ARC4.new(self.key, 256) ct_drop = cipher_drop.encrypt(self.data[:16]) ct = self.cipher.encrypt(self.data)[256:256+16] self.assertEquals(ct_drop, ct)
def decrypt_rc4(enckey, data): cipher = ARC4.new(enckey) # set the ciper return cipher.decrypt(data.decode('hex')) # decrpyt the data
#!/usr/bin/env python3 import sys import codecs from Crypto.Cipher import ARC4 from tools import get_ransom_data if len(sys.argv) < 2: print("Usage: %s ransom.txt" % sys.argv[0], file=sys.stderr) sys.exit(1) data = get_ransom_data(sys.argv[1], "PC DATA") decr = ARC4.new(b".oj=294~!z3)9n-1,8^)o((q22)lb$").decrypt(data) print(codecs.decode(decr,"utf-16le"))
def decrypt_CB(self): secret = Bootloader.SECRET_1BL key = hmac.new(secret, self.salt, sha).digest()[0:0x10] cb = self.data[0:0x10] + key + RC4.new(key).decrypt(self.data[0x20:]) self.data = cb
def encrypt_CG(self, cf, random): secret = cf.key key = hmac.new(secret, random, sha).digest()[0:0x10] cg = self.data[:0x10] + random + RC4.new(key).encrypt(self.data[0x20:]) self.data = cg
def setUp(self): self.cipher = ARC4.new(self.key)
def decrypt(cls, key_name): k = cls.get_by_key_name(str(key_name)) if not k: raise KeymasterError("Keymaster has no secret for %s" % key_name) return ARC4.new(os.environ['APPLICATION_ID']).encrypt(k.secret)
#Jessica Bailey, Cory Kucera, Roxyn Dively import socket import sys import os import glob import zlib from Crypto.Cipher import ARC4 enc = ARC4.new('AKEY2016') encryptFlag = 0 compressFlag = 0 binaryFlag = 0 buff = 1024 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = '172.20.10.2' port = 12345 address = (host, port) s.connect(('127.0.0.1',port)) print "Socket successfully connected" s.send(host) #send message 1 print s.recv(buff) #receive message 2 #Reusable function used to send files to the client def Upload_File(filename, encryptFlag, compressFlag, binaryFlag): s.send(filename) #send filename to upload s.recv(buff) #receive acknowledgement of filename if os.path.exists(filename):
def seed(key): global ARC4Cipher ARC4Cipher = ARC4.new(key)
# -*- coding:utf-8 -*- """ created by server on 14-7-31下午6:45. """ # from test.pycrypto_test.pycrypto import PyCrypto_RC4 # # a1 = PyCrypto_RC4('123456789123456789') # # str = a1.encrypt('f**k') # # a2 = PyCrypto_RC4('123456789123456789') # # print a2.decrypt(str) from Crypto.Cipher import ARC4 a1 = ARC4.new('1234544523453245234') str = a1.encrypt('f**k') # a2 = ARC4.new('1234544523453245234') print a1.decrypt(str)
def decrypt_CE(self, cd): secret = cd.key assert secret is not None, 'No key given to decrypt_CE' key = hmac.new(secret, self.salt, sha).digest()[0:0x10] ce = self.data[0:0x10] + key + RC4.new(key).decrypt(self.data[0x20:]) self.data = ce
def decrypt_rc4(key, data): cipher = ARC4.new(key) return cipher.decrypt(data)
from Crypto.Cipher import ARC4 f = open('secret.txt') key = f.readline().strip() o = open('challenge.txt', 'w') f = open('book.txt') for line in f: cipher = ARC4.new(key) print >> o, cipher.encrypt(line).encode('hex') print "Wrote challenge.txt"
def _parse_connect_response(self): # want and treat op_accept or op_cond_accept or op_accept_data b = self.recv_channel(4) while bytes_to_bint(b) == self.op_dummy: b = self.recv_channel(4) if bytes_to_bint(b) == self.op_reject: raise OperationalError('Connection is rejected') op_code = bytes_to_bint(b) if op_code == self.op_response: return self._parse_op_response() # error occured b = self.recv_channel(12) self.accept_version = byte_to_int(b[3]) self.accept_architecture = bytes_to_bint(b[4:8]) self.accept_type = bytes_to_bint(b[8:]) self.lazy_response_count = 0 if op_code == self.op_cond_accept or op_code == self.op_accept_data: ln = bytes_to_bint(self.recv_channel(4)) data = self.recv_channel(ln, word_alignment=True) ln = bytes_to_bint(self.recv_channel(4)) self.accept_plugin_name = self.recv_channel(ln, word_alignment=True) is_authenticated = bytes_to_bint(self.recv_channel(4)) ln = bytes_to_bint(self.recv_channel(4)) self.recv_channel(ln, word_alignment=True) # keys if is_authenticated == 0: if self.accept_plugin_name in (b'Srp256', b'Srp'): hash_algo = { b'Srp256': hashlib.sha256, b'Srp': hashlib.sha1, }[self.accept_plugin_name] user = self.user if len(user) > 2 and user[0] == user[-1] == '"': user = user[1:-1] user = user.replace('""', '"') else: user = user.upper() if len(data) == 0: # send op_cont_auth self._op_cont_auth( srp.long2bytes(self.client_public_key), self.accept_plugin_name, self.plugin_list, b'') b = self.recv_channel(4) if bytes_to_bint(b) == self.op_response: self._parse_op_response() # error occured # parse op_cont_auth assert bytes_to_bint(b) == self.op_cont_auth ln = bytes_to_bint(self.recv_channel(4)) data = self.recv_channel(ln, word_alignment=True) ln = bytes_to_bint(self.recv_channel(4)) self.recv_channel(ln, word_alignment=True) # plugin_name ln = bytes_to_bint(self.recv_channel(4)) self.recv_channel(ln, word_alignment=True) # plugin_list ln = bytes_to_bint(self.recv_channel(4)) self.recv_channel(ln, word_alignment=True) # keys ln = bytes_to_int(data[:2]) server_salt = data[2:ln + 2] server_public_key = srp.bytes2long( hex_to_bytes(data[4 + ln:])) auth_data, session_key = srp.client_proof( self.str_to_bytes(user), self.str_to_bytes(self.password), server_salt, self.client_public_key, server_public_key, self.client_private_key, hash_algo) elif self.accept_plugin_name == b'Legacy_Auth': auth_data = self.str_to_bytes(get_crypt(self.password)) session_key = b'' else: raise OperationalError('Unknown auth plugin %s' % (self.accept_plugin_name)) else: auth_data = b'' session_key = b'' if op_code == self.op_cond_accept: self._op_cont_auth(auth_data, self.accept_plugin_name, self.plugin_list, b'') (h, oid, buf) = self._op_response() if self.wire_crypt and session_key: self._op_crypt() self.sock.set_translator(ARC4.new(session_key), ARC4.new(session_key)) (h, oid, buf) = self._op_response() else: # use later _op_attach() and _op_create() self.auth_data = auth_data else: assert op_code == self.op_accept
menu = """ +--------- MENU ---------+ | | | [1] Show FLAG | | [2] Encrypt Something | | [3] Exit | | | +------------------------+ """ print(menu) while 1: choice = input("\n[?] Enter your choice: ") if choice == '1': cipher = ARC4.new(KEY) enc = cipher.encrypt(FLAG.encode()).hex() print(f"\n[+] Encrypted FLAG: {enc}") elif choice == '2': plaintext = input("\n[*] Enter Plaintext: ") cipher = ARC4.new(KEY) ciphertext = cipher.encrypt(plaintext.encode()).hex() print(f"[+] Your Ciphertext: {ciphertext}") else: print("\n:( See ya later!") exit(0)
def decrypt(data): rc4_demo = ARC4.new(binascii.unhexlify("404142434445464748494A4B4C4D4E4F")) data = binascii.unhexlify(data) res = rc4_demo.decrypt(data) return res.hex()
def _rc4_encryption_oracle(request: bytes) -> bytes: fresh_key = urandom(16) cipher = ARC4.new(fresh_key) return cipher.encrypt(request + cookie)
def decrypt_RC4(enckey, data): cipher = ARC4.new(enckey) return cipher.decrypt(data)
rc4_demo = ARC4.new(binascii.unhexlify("404142434445464748494A4B4C4D4E4F")) data = binascii.unhexlify(data) res = rc4_demo.encrypt(data) return res.hex() def decrypt(data): rc4_demo = ARC4.new(binascii.unhexlify("404142434445464748494A4B4C4D4E4F")) data = binascii.unhexlify(data) res = rc4_demo.decrypt(data) return res.hex() for i in range(1000): test_data = get_random_16bytes() # 加密函数 func1 = encrypt func2 = decrypt # def ms_time_count(func1, func2, alg, mode, data, key, n): ms_time_count(func1,func2 ,alg='rc4',mode='',data=test_data,key='404142434445464748494A4B4C4D4E4F',n=i) for i in range(5): t1 = time.time() for j in range(10000): data = get_random_16bytes() rc4_demo = ARC4.new(binascii.unhexlify("404142434445464748494A4B4C4D4E4F")) data = binascii.unhexlify(data) rc4_demo.encrypt(data) t2 = time.time() print(t2-t1)
def decrypt_in_arc4(key, msg): arc4 = ARC4.new(key) return arc4.decrypt(msg)
def _decrypt(self, data, key): key_ = MD5.new(key).hexdigest() cipher = ARC4.new(key_) return cipher.decrypt(data)
def token_decode(key, token): obj = ARC4.new(key) return obj.decrypt(base64.b64decode(token))
def bind(self, uuid, alter = 0, bogus_binds = 0): bind = MSRPCBind() # Standard NDR Representation NDRSyntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0') # NDR 64 NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0') #item['TransferSyntax']['Version'] = 1 ctx = self._ctx for i in range(bogus_binds): item = CtxItem() item['ContextID'] = ctx item['TransItems'] = 1 item['ContextID'] = ctx # We generate random UUIDs for bogus binds item['AbstractSyntax'] = generate() + stringver_to_bin('2.0') item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax) bind.addCtxItem(item) self._ctx += 1 ctx += 1 # The true one :) item = CtxItem() item['AbstractSyntax'] = uuid item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax) item['ContextID'] = ctx item['TransItems'] = 1 bind.addCtxItem(item) packet = MSRPCHeader() packet['type'] = MSRPC_BIND if alter: packet['type'] = MSRPC_ALTERCTX if (self.__auth_level != ntlm.NTLM_AUTH_NONE): if (self.__username is None) or (self.__password is None): self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash = self._transport.get_credentials() auth = ntlm.getNTLMSSPType1('', self.__domain, True, isDCE = True, use_ntlmv2 = self._transport.doesSupportNTLMv2()) auth['auth_level'] = self.__auth_level auth['auth_ctx_id'] = self._ctx + 79231 pad = (8 - (len(packet.get_packet()) % 8)) % 8 if pad != 0: packet['pduData'] = packet['pduData'] + '\xFF'*pad auth['auth_pad_len']=pad packet['auth_data'] = str(auth) packet['pduData'] = str(bind) packet['call_id'] = self.__callid self._transport.send(packet.get_packet()) s = self._transport.recv() if s != 0: resp = MSRPCHeader(s) else: return 0 #mmm why not None? if resp['type'] == MSRPC_BINDACK or resp['type'] == MSRPC_ALTERCTX_R: bindResp = MSRPCBindAck(str(resp)) elif resp['type'] == MSRPC_BINDNAK: resp = MSRPCBindNak(resp['pduData']) status_code = resp['RejectedReason'] if rpc_status_codes.has_key(status_code): raise Exception(rpc_status_codes[status_code], resp) else: raise Exception('Unknown DCE RPC fault status code: %.8x' % status_code, resp) else: raise Exception('Unknown DCE RPC packet type received: %d' % resp['type']) # check ack results for each context, except for the bogus ones for ctx in range(bogus_binds+1,bindResp['ctx_num']+1): result = bindResp.getCtxItem(ctx)['Result'] if result != 0: msg = "Bind context %d rejected: " % ctx msg += rpc_cont_def_result.get(result, 'Unknown DCE RPC context result code: %.4x' % result) msg += "; " reason = bindResp.getCtxItem(ctx)['Reason'] msg += rpc_provider_reason.get(reason, 'Unknown reason code: %.4x' % reason) if (result, reason) == (2, 1): # provider_rejection, abstract syntax not supported msg += " (this usually means the interface isn't listening on the given endpoint)" raise Exception(msg, resp) self.__max_xmit_size = bindResp['max_tfrag'] if self.__auth_level != ntlm.NTLM_AUTH_NONE: response, randomSessionKey = ntlm.getNTLMSSPType3(auth, bindResp['auth_data'], self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, True, use_ntlmv2 = self._transport.doesSupportNTLMv2()) response['auth_ctx_id'] = self._ctx + 79231 response['auth_level'] = self.__auth_level self.__flags = response['flags'] if self.__auth_level in (ntlm.NTLM_AUTH_CONNECT, ntlm.NTLM_AUTH_PKT_INTEGRITY, ntlm.NTLM_AUTH_PKT_PRIVACY): if self.__flags & ntlm.NTLMSSP_NTLM2_KEY: self.__clientSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey) self.__serverSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey,"Server") self.__clientSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey) self.__serverSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey,"Server") # Preparing the keys handle states cipher3 = ARC4.new(self.__clientSealingKey) self.__clientSealingHandle = cipher3.encrypt cipher4 = ARC4.new(self.__serverSealingKey) self.__serverSealingHandle = cipher4.encrypt else: # Same key for everything self.__clientSigningKey = randomSessionKey self.__serverSigningKey = randomSessionKey self.__clientSealingKey = randomSessionKey self.__serverSealingKey = randomSessionKey cipher = ARC4.new(self.__clientSigningKey) self.__clientSealingHandle = cipher.encrypt self.__serverSealingHandle = cipher.encrypt self.__sequence = 0 auth3 = MSRPCHeader() auth3['type'] = MSRPC_AUTH3 auth3['auth_data'] = str(response) # Use the same call_id self.__callid = resp['call_id'] auth3['call_id'] = self.__callid self._transport.send(auth3.get_packet(), forceWriteAndx = 1) self.__callid += 1 return resp # means packet is signed, if verifier is wrong it fails
def decrypt(self, key=None): if key is None: key = conf.wepkey if key: c = ARC4.new(self.iv + key) self.add_payload(LLC(c.decrypt(self.wepdata)))
from Crypto.Cipher import ARC4 key = "".encode("hex") response = "" enc = ARC4.new(key) response = response.decode("base64") print enc.decrypt(response)