예제 #1
0
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)")
예제 #2
0
파일: server.py 프로젝트: BullyBoy/sectalks
    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")
예제 #3
0
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
예제 #4
0
    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()
예제 #5
0
 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)
예제 #6
0
파일: middleware.py 프로젝트: lzimm/pervurs
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
예제 #7
0
 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)
예제 #8
0
 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)
예제 #9
0
 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
예제 #10
0
 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
예제 #11
0
파일: crypto.py 프로젝트: piggum/synapse
    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 )
예제 #12
0
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
예제 #13
0
  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]
예제 #14
0
파일: crypto.py 프로젝트: 0xc0da/impacket
 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)
예제 #15
0
    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
예제 #16
0
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]
예제 #17
0
 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'])
예제 #18
0
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
예제 #19
0
 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()
예제 #20
0
def getrc4encodehex(mapdata):
    tempkey = '123465'
    cipher = ARC4.new(tempkey)
    jsonstr = json.dumps(mapdata)
    msg = cipher.encrypt(jsonstr)
    hexstr = binascii.b2a_hex(msg[:])
    return hexstr
예제 #21
0
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
예제 #22
0
    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
예제 #23
0
def getrc4encodebase64(mapdata):
    tempkey = '123465'
    cipher = ARC4.new(tempkey)
    jsonstr = json.dumps(mapdata)
    msg = cipher.encrypt(jsonstr)
    base64str = base64.b64encode(msg)
    return base64str
예제 #24
0
파일: magicforms.py 프로젝트: ruiaf/website
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
예제 #25
0
파일: weave2.py 프로젝트: HearthSim/weave
	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)
예제 #26
0
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
예제 #27
0
    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
예제 #28
0
	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
예제 #29
0
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 )
예제 #30
0
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:])
예제 #31
0
#Jessica Bailey, Cory Kucera, Roxyn Dively
import socket
import sys
import os
from subprocess import call
from subprocess import check_output
import glob
import zlib
import binascii
from Crypto.Cipher import ARC4
enc = ARC4.new('AKEY2016')
encryptFlag = 0
compressFlag = 0
binaryFlag = 0



#Function for Registered user login
def Login(user):
	passwd = c.recv(1024) #receive password
	c.send("Password received.") #send password ack
	c.recv(1024) #receive and print login message
	if users.has_key(user):
		if str(users[user]) == passwd:
			c.send("accept") #send accept authentication
			user_tracking.append(user)
			c.recv(1024) #receive ack for accept
			print "User %s connected to server." %(user)
			login_loop['login_switch'] = False
			#login_switch = False
			#return login_switch
예제 #32
0
def rc4_transform(data, key):
	arc4 = ARC4.new(key)
	return arc4.encrypt(data)
예제 #33
0
#import os
import sys
from Crypto.Cipher import ARC4

decipher = ARC4.new(sys.argv[1])
with open(sys.argv[2], "rb") as file:
    data = file.read()
plaintext = decipher.decrypt(data)

f = open(sys.argv[3], "wb")
f.write(plaintext)
f.close()
예제 #34
0
파일: Crypto_rc4.py 프로젝트: wgf4242/text
def rc4_encrypt(plain, key):
    cipher = ARC4.new(key)
    msg = cipher.encrypt(plain)
    return base64.b64encode(msg)
예제 #35
0
 def decrypt(ciphertext):
     salt, ciphertext = list(map(b64decode, ciphertext.split('$')))
     arc4 = ARC4.new(salt + settings.SECRET_KEY)
     plaintext = arc4.decrypt(ciphertext)
     plaintext = plaintext[3:3 + int(plaintext[:3].strip())]
     return plaintext.decode('utf8')
예제 #36
0
파일: ciphers.py 프로젝트: PyCQA/bandit
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.backends import default_backend
from struct import pack

key = b'Sixteen byte key'
iv = Random.new().read(pycrypto_arc2.block_size)
cipher = pycrypto_arc2.new(key, pycrypto_arc2.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')
cipher = pycryptodomex_arc2.new(key, pycryptodomex_arc2.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')

key = b'Very long and confidential key'
nonce = Random.new().read(16)
tempkey = SHA.new(key+nonce).digest()
cipher = pycrypto_arc4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')
cipher = pycryptodomex_arc4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')

iv = Random.new().read(bs)
key = b'An arbitrarily long key'
plaintext = b'docendo discimus '
plen = bs - divmod(len(plaintext),bs)[1]
padding = [plen]*plen
padding = pack('b'*plen, *padding)
bs = pycrypto_blowfish.block_size
cipher = pycrypto_blowfish.new(key, pycrypto_blowfish.MODE_CBC, iv)
msg = iv + cipher.encrypt(plaintext + padding)
bs = pycryptodomex_blowfish.block_size
cipher = pycryptodomex_blowfish.new(key, pycryptodomex_blowfish.MODE_CBC, iv)
예제 #37
0
 def decrypt_rc4(self, objid, genno, data):
     key = self.key + struct.pack('<L', objid)[:3] + struct.pack(
         '<L', genno)[:2]
     hash = md5.md5(key)
     key = hash.digest()[:min(len(key), 16)]
     return ARC4.new(key).decrypt(data)
예제 #38
0
파일: RC4.py 프로젝트: minjiang93/RC4
def dec(key,msg):
		return ARC4.new(key).decrypt(msg)
예제 #39
0
파일: RC4.py 프로젝트: minjiang93/RC4
def enc(key,p):
		return ARC4.new(key).encrypt(p)
예제 #40
0
 def get_cipher(self, iv):
     md5 = hashlib.md5()
     md5.update(self.key)
     md5.update(iv)
     rc4_key = md5.digest()
     return ARC4.new(rc4_key)
예제 #41
0
def decrypt_RC4(enckey, data):
	cipher = ARC4.new(enckey) # set the ciper
	return cipher.decrypt(data) # decrypt the data
예제 #42
0
def decrypt_payload(payload_encrypted, password):
    obj = ARC4.new(password)
    payload_decrypted = obj.decrypt(payload_encrypted)

    return payload_decrypted
예제 #43
0
 def encrypt(cls, data, key):
     """Encrypt and decrypt are the same for RC4."""
     rc4 = ARC4.new(key)
     return rc4.encrypt(data)
예제 #44
0
def encrypt_CF(CF, random):
    secret = secret_1BL
    key = hmac.new(secret, random, sha).digest()[0:0x10]
    CF_key = CF[0x330:0x330 + 0x10]
    CF = CF[0:0x20] + random + RC4.new(key).encrypt(CF[0x30:])
    return CF, CF_key
예제 #45
0
def decrypt_password(encrypted_password):
    from Crypto.Cipher import ARC4
    from base64 import b64decode
    memorized_password = getpass("Enter encryption password: ")
    cipher = ARC4.new(memorized_password)
    return cipher.decrypt(b64decode(encrypted_password))
예제 #46
0
def encrypt_CG(CG, CF_key, random):
    secret = CF_key
    key = hmac.new(secret, random, sha).digest()[0:0x10]
    CG = CG[:0x10] + random + RC4.new(key).encrypt(CG[0x20:])
    return CG
예제 #47
0
def encrypt_CD(CD, CB_key, random):
    secret = CB_key
    key = hmac.new(secret, random, sha).digest()[0:0x10]
    CD = CD[0:0x10] + random + RC4.new(key).encrypt(CD[0x20:])
    return CD, key
예제 #48
0
def encrypt_CE(CE, CD_key, random):
    secret = CD_key
    key = hmac.new(secret, random, sha).digest()[0:0x10]
    CE = CE[0:0x10] + random + RC4.new(key).encrypt(CE[0x20:])
    return CE
예제 #49
0
def decrypt_CG(CG, CF):
    secret = CF[0x330:0x330 + 0x10]
    key = hmac.new(secret, CG[0x10:0x20], sha).digest()[0:0x10]
    CG = CG[:0x10] + key + RC4.new(key).decrypt(CG[0x20:])
    return CG
예제 #50
0
def encrypt_CB(CB, random):
    secret = secret_1BL
    key = hmac.new(secret, random, sha).digest()[0:0x10]
    CB = CB[0:0x10] + random + RC4.new(key).encrypt(CB[0x20:])
    return CB, key
예제 #51
0
def decrypt_CE(CE, CD):
    secret = CD[0x10:0x20]
    key = hmac.new(secret, CE[0x10:0x20], sha).digest()[0:0x10]
    CE = CE[0:0x10] + key + RC4.new(key).decrypt(CE[0x20:])
    return CE
예제 #52
0
def decrypt_CF(CF):
    secret = secret_1BL
    key = hmac.new(secret, CF[0x20:0x30], sha).digest()[0:0x10]
    CF = CF[0:0x20] + key + RC4.new(key).decrypt(CF[0x30:])
    return CF
예제 #53
0
from Crypto.Cipher import ARC4
import time

cipher = ARC4.new("sample key of any length")
inputFilename = 'frankenstein.txt'
data = open(inputFilename).read()

start_time_encrypt = time.time()
encrypted_data = cipher.encrypt(data)
print("--- %s seconds ---" % (time.time() - start_time_encrypt))
outputFilename = 'frankenstein.encrypted.txt'
outputFileObj = open(outputFilename, 'wb')
outputFileObj.write(encrypted_data)
outputFileObj.close()

start_time_decrypt = time.time()
print(cipher.decrypt(encrypted_data))
print("--- %s seconds ---" % (time.time() - start_time_decrypt))
#print (encrypted_data)
#print (cipher.decrypt(encrypted_data))
예제 #54
0
def decrypt_rc4(enckey, data):
    cipher = ARC4.new(enckey)  # set the ciper
    return cipher.decrypt(data.decode('hex'))  # decrpyt the data
예제 #55
0
def decrypt(ciphertext, key):
    
    cipher = ARC4.new(key)
    plaintext = cipher.decrypt(ciphertext[ARC4.block_size:])
    return plaintext.rstrip(b"\0")
예제 #56
0
def RC4(key, data):
    cipher = ARC4.new(key)
    return cipher.decrypt(data)
예제 #57
0
def encrypt(message, key, key_size=256):
    
    message = pad(message)
    cipher = ARC4.new(key)
    return cipher.encrypt(message)
예제 #58
0
파일: Crypto_rc4.py 프로젝트: wgf4242/text
def rc4_decrypt(msg, key):
    cipher = ARC4.new(key)
    txt = base64.b64decode(msg)
    return cipher.decrypt(txt)
예제 #59
0
def encrypt_payload(payload, password):
    obj = ARC4.new(password)
    payload_encrypted = obj.encrypt(payload)

    return payload_encrypted
예제 #60
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 23:25:57 2021

@author: antonio
"""

from Crypto.Cipher import ARC4

plaintext = "Este es el  mensaje a cifrar con RC4"
key = 'Esta es la llave'

cipher = ARC4.new(key)
cifrado = cipher.encrypt(plaintext)
print("Mensaje cifrado: ", cifrado)

cipher = ARC4.new(key)
descifrado = cipher.decrypt(cifrado).decode()
print("Mensaje descifrado: ", descifrado)