Ejemplo n.º 1
0
def main():
    plain_text = "meet me after the toga party"
    n = 8
    N = 2**n
    K = "hello world key"
    k = 4  # Key size in bytes
    secret_key = list(map(lambda x: ord(x), sample(K, k)))
    initial_vector = sample(range(N), k)
    # key = list(range(k))    # Key definition
    key = secret_key + initial_vector  # Key definition
    # S-boxes definition
    sbox = list(range(N))
    sboxes = [sbox[:N // 2], sbox[N // 2:]]

    # RC4 function call to encrypt
    encrypt, key_stream = rc4(key, k, plain_text, N, sboxes)

    # Show the encryption
    showStatus("Encryption", plain_text, key, key_stream, encrypt)

    # Reinitialize sboxes
    sboxes = [sbox[:N // 2], sbox[N // 2:]]
    # RC4 function call to decrypt
    decrypt, key_stream = rc4(key, k, encrypt, N, sboxes)
    # Show the decryption
    showStatus("Decryption", encrypt, key, key_stream, decrypt)
Ejemplo n.º 2
0
def current_user(request):
    account = request.META.get('HTTP_X_AC')
    rid = request.META.get('HTTP_X_RID')

    try:
        if account:
            account = base64.b64decode(account)
            account = rc4.rc4(account, GAME_KEY)
            user = User.objects.filter(account=account).first()
        elif rid:
            rid = base64.b64decode(rid)
            rid = rc4.rc4(rid, GAME_KEY)
            user = User.objects.filter(rid=rid).first()
        else:
            return jsonify(data=None,
                           success=False,
                           errMsg='Lack of user info.')
    except:
        return jsonify(data=None,
                       success=False,
                       errMsg='User info decode error.')

    if not user:
        return jsonify(data=None, success=False, errMsg="User is not logined.")
    return user
Ejemplo n.º 3
0
def main():
    K = [4, 7, 5, 5]
    N = 8
    cur_i = 4
    z = 6

    K = guess_keys(N, K, cur_i, z)
    rc4(N, K)
Ejemplo n.º 4
0
def find_key6(ct):
    text = ct[:20]
    max_score = 0
    max_score_key = ''
    rating = 0
    for i in range(start, end):
        rating = (1 * count_printable(rc4.rc4(str(i), text))) + (
            .75 * count_letters((rc4.rc4(str(i), text)))) + (englishy(
                (rc4.rc4(str(i), text))))
        if rating >= max_score:
            max_score = rating
            max_score_key = str(i)
    return max_score_key
Ejemplo n.º 5
0
    def decoder(self, pkt, keyText):
        """Take a packet with [Dot11WEP] and apply RC4 to get the [LLC]"""
        ## Re-use the IV for comparative purposes
        # <class 'bytes'>
        # b'z\x00\x00\x124Vx\x90'
        # print('DECODING')
        # print([pkt[Dot11WEP].iv])
        # print(str([pkt[Dot11WEP].iv]))
        # print(type(pkt[Dot11WEP].iv))
        iVal = pkt[Dot11WEP].iv
        # print(iVal)
        # print(keyText)
        seed = self.seedGen(iVal, keyText)

        ## Remove the FCS so that we maintain packet size
        pload = self.pt.byteRip(pkt[Dot11WEP],
                                order='last',
                                qty=4,
                                chop=True,
                                output='str')

        ## Return the stream, iv and seed
        # print('\n\n\n')
        # print(type(pload))
        # print('\n')
        # print(pload)
        # print('\n\n\n')
        # print(type(seed))
        # print(seed)
        return rc4(Dot11WEP(pload).wepdata, seed), iVal, seed
Ejemplo n.º 6
0
 def _handle_in(self, packet):
     if packet['opcode'] == 2:
         self._out_key = packet['key']
         self._out_cipher = rc4.rc4(hmac.new(self._login, self._hash + self._out_key).digest())
     elif packet['opcode'] == 0:
         for opcode, data in packet['packets']:
             self.log_packet('s', opcode, data)
Ejemplo n.º 7
0
    def encoder(self, pkt, iVal, keyText):
        ## Calculate the WEP Integrity Check Value (ICV)
        # wepICV = self.pt.endSwap(hex(crc32(str(pkt[LLC])) & 0xffffffff))
        wepICV = self.pt.endSwap(
            hex(
                crc32(
                    binascii.unhexlify(
                        hexstr(pkt[LLC], onlyhex=1).replace(' ', '')))
                & 0xffffffff))

        ## Concatenate ICV to the [LLC]
        # stream = str(pkt[LLC]) + binascii.unhexlify(wepICV.replace('0x', ''))
        stream = binascii.unhexlify(
            hexstr(pkt[LLC], onlyhex=1).replace(' ', '')) + binascii.unhexlify(
                wepICV.replace('0x', ''))

        # iVal = pkt[Dot11WEP].iv.decode('latin1')
        # seed = self.seedGen(iVal, keyText).decode('latin1')
        # return rc4(pkt.wepdata.decode('latin1'), iVal + seed), iVal, seed

        ## Return the encrypted data
        # return rc4(stream, self.seedGen(iVal, keyText))
        newStream = []
        newStream.append(" ".join(
            map(lambda stream: "%02x" % ord(stream), stream)))
        newStream = "  ".join(newStream)
        # return rc4(newStream.decode('latin1'), self.seedGen(iVal, keyText))
        return rc4(stream.decode('latin1'), self.seedGen(iVal, keyText))
Ejemplo n.º 8
0
def processClass(baseDir, className, strings, decoderClass, decoderMethod):
    fileName = baseDir[:-1] + '/' + className
    className = className[:-len('.smali')]
    with open(fileName, 'r') as smaliFile:
        lines = smaliFile.readlines()

    key = generateKey()
    encoder = rc4.rc4(key)

    stringNames = []
    encStrings = []
    index = 0

    for lineNum in strings.keys():
        stringNames.append(generateStringFieldName(index))
        encStrings.append(encoder.encode(strings[lineNum]))
        newLine = getStringReplaceLine(lines[lineNum], stringNames[index],
                                       className)
        lines[lineNum] = newLine
        index += 1

    appendFields(lines, stringNames)
    generateStaticConstructor(lines, className, key, stringNames, encStrings,
                              decoderClass, decoderMethod)

    with open(fileName, 'w') as smaliFile:
        smaliFile.writelines(lines)
Ejemplo n.º 9
0
def main(args, env):
    pe = pefile.PE(args.file)
    assert (len(pe.DIRECTORY_ENTRY_RESOURCE.entries) == 1)
    resource_dir = pe.DIRECTORY_ENTRY_RESOURCE.entries[0]
    resources = {}
    for res in resource_dir.directory.entries:
        name = str(res.name)
        assert (len(res.directory.entries) == 1)
        size = res.directory.entries[0].data.struct.Size
        offset = res.directory.entries[0].data.struct.OffsetToData
        data = pe.get_data(offset, size)
        resources[name] = data

    try:
        key = resources['KEY']
        CT = resources[args.resource]
        PT = rc4.rc4(CT, key)  # RC4 Decrypt Resource
        uncompressed = lib.lznt1.dCompressBuf(PT)  # LZNT1 Decompress
        payload_pe = pefile.PE(data=uncompressed)
        assert (len(payload_pe.get_warnings()) == 0
                )  # Verify uncompressed data is a valid PE
        payload_data = payload_pe.trim()
        with file(args.resource, "wb") as f:
            f.write(payload_data)
        print("Successfully Dumped payload {}".format(args.resource))
        exit()
    except Exception as e:
        print("Failed to dump payload {}".format(args.resource))
        return 1
Ejemplo n.º 10
0
def processClass(baseDir, className, strings, decoderClass, decoderMethod):
    fileName = baseDir[:-1] + '/' + className
    className = className[:-len('.smali')]
    with open(fileName, 'r') as smaliFile:
        lines = smaliFile.readlines()

    key = generateKey();
    encoder = rc4.rc4(key)
    
    stringNames = []
    encStrings = []
    index = 0;
    
    for lineNum in strings.keys():
        stringNames.append(generateStringFieldName(index))
        encStrings.append(encoder.encode(strings[lineNum]))
        newLine = getStringReplaceLine(lines[lineNum], stringNames[index], className)        
        lines[lineNum] = newLine
        index += 1
    
    appendFields(lines, stringNames)
    generateStaticConstructor(lines, className, key, stringNames, encStrings, decoderClass, decoderMethod)
    
    with open(fileName, 'w') as smaliFile:
        smaliFile.writelines(lines)
Ejemplo n.º 11
0
 def _handle_out(self, packet):
     if packet['opcode'] == 2:
         self._in_key = packet['key']
         self._in_cipher = rc4.rc4(hmac.new(self._login, self._hash + self._in_key).digest())
         self._in_decomp = mppc.MPPCDecoder()
     elif packet['opcode'] == 3:
         self._login = packet['login']
         self._hash = packet['hash']
Ejemplo n.º 12
0
def rc4_permutation(bitarray):
    permutation_len = len(bitarray)
    permutation_list = rc4(bitarray.bytes,
                           state_len=len(bitarray)).get_permutation_list()
    output_data = BitArray()
    for i in range(permutation_len):
        output_data.append(BitArray(bin=bitarray.bin[permutation_list[i]]))
    return output_data
Ejemplo n.º 13
0
 def _handle_in(self, packet):
     if packet['opcode'] == 2:
         self._out_key = packet['key']
         self._out_cipher = rc4.rc4(
             hmac.new(self._login, self._hash + self._out_key).digest())
     elif packet['opcode'] == 0:
         for opcode, data in packet['packets']:
             self.log_packet('s', opcode, data)
Ejemplo n.º 14
0
def run(keyFile, outputFile, inputFile):
    with open(keyFile, "rb") as keyStream:
        key = keyStream.read()
        with open(inputFile, "rb") as inputStream:
            data = inputStream.read()
            output = rc4(key, data)
            with open(outputFile, "wb") as outputStream:
                outputStream.write(output)
Ejemplo n.º 15
0
 def _handle_out(self, packet):
     if packet['opcode'] == 2:
         self._in_key = packet['key']
         self._in_cipher = rc4.rc4(
             hmac.new(self._login, self._hash + self._in_key).digest())
         self._in_decomp = mppc.MPPCDecoder()
     elif packet['opcode'] == 3:
         self._login = packet['login']
         self._hash = packet['hash']
Ejemplo n.º 16
0
def encrypt_pe_data(data, key):
    encrypted = data
    if args['data_compress']:
        #encrypted = aplib.aplib_compress(encrypted).do()
        encrypted = aplib2.pack(encrypted)
    encrypted = rc4.rc4(encrypted, key)
    if args['data_base64']:
        encrypted = base64.b64encode(encrypted)
    return encrypted
Ejemplo n.º 17
0
    def encoder(self, pkt, iVal, keyText):
        ## Calculate the WEP Integrity Check Value (ICV)
        wepICV = self.pt.endSwap(hex(crc32(str(pkt[LLC])) & 0xffffffff))

        ## Concatenate ICV to the [LLC]
        stream = str(pkt[LLC]) + binascii.unhexlify(wepICV.replace('0x', ''))

        ## Return the encrypted data
        return rc4(stream, self.seedGen(iVal, keyText))
Ejemplo n.º 18
0
def encode(text, key):
    keystream = rc4.prga(rc4.ksa(key))
    J = random.randint(0, 255)
    k = [keystream.__next__() for i in range(255)]
    k = "".join([chr(ki) for ki in k])

    crc4 = rc4.rc4(text, keystream)
    C1 = viginere.encrypt(crc4[:J], k[:J])
    C2 = viginere.encrypt(crc4[J:], k[J:])
    return C1 + C2 + str(J).zfill(3)
Ejemplo n.º 19
0
    def get_file_contents(self, filename, keysize=0):
        with open(filename, 'rb') as f:
            data = f.read()

        if keysize:
            key = self.generate_key(keysize)
            rc4.rc4_setkey(key)
            data = key + rc4.rc4(data)

        return data
Ejemplo n.º 20
0
    def get_file_contents(self, filename, keysize=0):
        with open(filename, 'rb') as f:
            data = f.read()

        if keysize:
            key = self.generate_key(keysize)
            rc4.rc4_setkey(key)
            data = key + rc4.rc4(data)

        return data
Ejemplo n.º 21
0
def system_info(data, key):
    blob = b64decode(data, '_-')
    cryptobj = rc4(key=key)
    decrypted = cryptobj.crypt(blob)
    (hostname, username, ip, proxy, id_, unknown) = decrypted.split('|')
    chop.tsprnt("Beacon:")
    chop.tsprnt("\tHostname: %s" % hostname)
    chop.tsprnt("\tUsername: %s" % username)
    chop.tsprnt("\tIP: %s" % ip)
    chop.tsprnt("\tID: %s" % id_)
    chop.tsprnt("\tUnknown: %s" % binascii.hexlify(unknown))
Ejemplo n.º 22
0
def decode(text, key):
    J = int(text[-3:])
    text = text[:-3]
    keystream = rc4.prga(rc4.ksa(key))
    k = [keystream.__next__() for i in range(255)]
    k = "".join([chr(ki) for ki in k])

    C1 = viginere.decrypt(text[:J], k[:J])
    C2 = viginere.decrypt(text[J:], k[J:])
    crc4 = rc4.rc4(C1 + C2, keystream)
    return crc4
Ejemplo n.º 23
0
def cifrar(senha, octetos):
    ''' Cifrar octetos usando algoritmo RC4 como no Ciphersaber 2

    O Ciphersaber 2 usa um vetor inicial de 10 octetos aleatórios concatenado
    à senha do usuário, e 20 iterações no laço de inicialização do RC4.

    fonte: http://ciphersaber.gurus.com/faq.html#cs2
    '''
    vetor_inicial = urandom(10)
    senha = bytes(senha, CODIF) + vetor_inicial
    return vetor_inicial + rc4(senha, octetos, 20)
Ejemplo n.º 24
0
def system_info(data, key):
    blob = b64decode(data, '_-')
    cryptobj = rc4(key=key)
    decrypted = cryptobj.crypt(blob)
    (hostname, username, ip, proxy, id_, unknown) = decrypted.split('|')
    chop.tsprnt("Beacon:")
    chop.tsprnt("\tHostname: %s" % hostname)
    chop.tsprnt("\tUsername: %s" % username)
    chop.tsprnt("\tIP: %s" % ip)
    chop.tsprnt("\tID: %s" % id_)
    chop.tsprnt("\tUnknown: %s" % binascii.hexlify(unknown))
Ejemplo n.º 25
0
 def parseC0p(self):
     self.RAW = self.getContent()
     originLen = self.getDataLen()
     self.parseTbl()
     if b"" != self.key:
         encedData = self.RAW[0x40:0x40 + originLen]
         self.plainData = rc4.rc4(
             encedData.decode("latin-1"),
             self.key.decode("latin-1")).encode("latin-1")
     else:
         self.plainData = self.RAW[0x40:0x40 + originLen]
     self.parseData()
Ejemplo n.º 26
0
def decypher(pkt):
    # Build seed and decypher
    key_stream = generate_seed(pkt[Dot11WEP].iv, args.pwd)
    decyphered = rc4(pkt[Dot11WEP].wepdata, key_stream)
    stack = LLC(decyphered)

    if not (IP in stack and UDP in stack and Raw in stack):
        return None

    del pkt[Dot11FCS].fcs
    del stack[IP].chksum
    del stack[UDP].chksum

    stack[IP].src, stack[IP].dst = stack[IP].dst, stack[IP].src
    pkt[Dot11FCS].addr1, pkt[Dot11FCS].addr3 = pkt[Dot11FCS].addr3, pkt[
        Dot11FCS].addr1

    pkt[Dot11WEP].wepdata = rc4(bytes(stack), key_stream)
    pkt[Dot11WEP].icv = crc32(bytes(stack))

    return pkt
Ejemplo n.º 27
0
    def __init__(self,
                 block_cipher_type="PCBC",
                 rc4_input_key='LucienD&IreneeD)',
                 initialization_numbe_bytes=b"ABCDEFGH"):

        self.block_cipher_type = block_cipher_type
        self.rc4_prng = rc4.rc4(rc4_input_key.encode())
        self.initialization_number = int.from_bytes(initialization_numbe_bytes,
                                                    "little")
        self.s_box_1 = self.rc4_prng.get_bytes(256)
        self.s_box_2 = self.rc4_prng.get_bytes(256)
        self.galois_field = pyfinite.ffield.FField(GALOIS_FIELD_SIZE)
Ejemplo n.º 28
0
    def generate_niraidata(self):
        print 'Generating niraidata'

        config = self.get_file_contents('../dependencies/config/release/en.prc')
        config += '\n\n' + self.get_file_contents('../dependencies/config/general.prc')
        key = self.generate_key(128)
        rc4.rc4_setkey(key)
        config = key + rc4.rc4(config)

        niraidata = 'CONFIG = %r' % config
        niraidata += '\nDC = %r' % self.get_file_contents('../dependencies/astron/dclass/crystal.dc', 128)
        self.add_module('niraidata', niraidata, compile=True)
Ejemplo n.º 29
0
    def generate_niraidata(self):
        print 'Generating niraidata'

        config = self.get_file_contents('../src/dependencies/config/release/en.prc')
        config += '\n\n' + self.get_file_contents('../src/dependencies/config/general.prc')
        key = self.generate_key(128)
        rc4.rc4_setkey(key)
        config = key + rc4.rc4(config)

        niraidata = 'CONFIG = %r' % config
        niraidata += '\nDC = %r' % self.get_file_contents('../src/dependencies/astron/dclass/crystal.dc', 128)
        self.add_module('niraidata', niraidata, compile=True)
Ejemplo n.º 30
0
def execution(path, body, module_data):
    key = module_data['key']
    opcodes = module_data['opcodes']
    verbose = module_data['verbose']

    blob = b64decode(path, '_-')
    cryptobj = rc4(key=key)
    decrypted = cryptobj.crypt(blob)
    chop.tsprnt("Command request from %s" % decrypted)
    if body:
        data = b64decode(body, '_-')
        cryptobj = rc4(key=key)
        decrypted = cryptobj.crypt(data)
        if len(decrypted) < 4:
            chop.tsprnt("Command response length invalid.")
            return
        opcode = struct.unpack('<I', decrypted[:4])[0]
        if opcode in opcodes:
            opcodes[opcode](decrypted[4:])
        else:
            chop.tsprnt("Unknown opcode (%i)" % opcode)
            if verbose:
                chop.tsprnt("Data:\n%s" % hexdump(decrypted))
Ejemplo n.º 31
0
def execution(path, body, module_data):
    key = module_data['key']
    opcodes = module_data['opcodes']
    verbose = module_data['verbose']

    blob = b64decode(path, '_-')
    cryptobj = rc4(key=key)
    decrypted = cryptobj.crypt(blob)
    chop.tsprnt("Command request from %s" % decrypted)
    if body:
        data = b64decode(body, '_-')
        cryptobj = rc4(key=key)
        decrypted = cryptobj.crypt(data)
        if len(decrypted) < 4:
            chop.tsprnt("Command response length invalid.")
            return
        opcode = struct.unpack('<I', decrypted[:4])[0]
        if opcode in opcodes:
            opcodes[opcode](decrypted[4:])
        else:
            chop.tsprnt("Unknown opcode (%i)" % opcode)
            if verbose:
                chop.tsprnt("Data:\n%s" % hexdump(decrypted))
Ejemplo n.º 32
0
    def decoder(self, pkt, keyText):
        """Take a packet with [Dot11WEP] and apply RC4 to get the [LLC]"""
        ## Re-use the IV for comparative purposes
        iVal = pkt[Dot11WEP].iv
        seed = self.seedGen(iVal, keyText)

        ## Remove the FCS so that we maintain packet size
        pload = self.pt.byteRip(pkt[Dot11WEP],
                                order='last',
                                qty=4,
                                chop=True,
                                output='str')

        ## Return the stream, iv and seed
        return rc4(Dot11WEP(pload).wepdata, seed), iVal, seed
Ejemplo n.º 33
0
def perform_action(args):
    """
    Parses the command line args and executes the encryption or decryption process
    @param args The argparse object of command line args
    """
    r = rc4()            # initialize the rc4 class object (r)
    r.key = args.key    # set the key for the object to be the value from the command line

    # if args.action is neither 'encrypt' nor 'decrypt', throw an error
    if args.action == "encrypt":
        if args.verbose:
            print "Encrypting files..."
        files = get_file_list(args.directory, args.recurse)
        for f in files:
            # don't run on already encrypted files, it will decrypt them
            if f[-4:] != ".enc":
                # add ".enc" to the end of each encrypted file
                if args.verbose:
                    print "Encrypting " + f
                enc_file = f + ".enc"
                # encrypt the files
                r.rc4main(f,enc_file)
                # if requested, delete the original files
                if args.cleanup:
                    if args.verbose:
                        print "Deleting " + f
                    os.remove(f)

    elif args.action == "decrypt":
        if args.verbose:
            print "Decrypting files..."
        files = get_file_list(args.directory, args.recurse)
        for f in files:
            if f[-4:] == ".enc":
                if args.verbose:
                    print "Decrypting " + f
                # method call to decrypt the files
                r.rc4main(f,f[:-4])
                if args.cleanup:
                    if args.verbose:
                        print "Deleting " + f
                    os.remove(f)

    # else, if neither argument is specified, throw an error
    else:
        print "ERROR: -a must specify either 'encrypt' or 'decrypt' as an argument"
        sys.exit(1)
Ejemplo n.º 34
0
 def encoder(self, pkt, iVal, keyText):
     ## Calculate the WEP Integrity Check Value (ICV)
     #wepICV = crc32(str(pkt[LLC]))
     wepICV = crc32(str(pkt[LLC])) & 0xffffffff
     plainText = str(pkt[LLC])
     
     #print 'wepICV is: ', wepICV
     #print 'hex of ^ is: ', hex(wepICV)
     #print 'unhexlify of ^ is: ', unhexlify(re.sub('0x', '', hex(wepICV)))
     #print 'repr of ^ is: ', repr(unhexlify(re.sub('0x', '', hex(wepICV))))
     #stream = plainText + str(wepICV)
     #stream = plainText + hex(wepICV)
     #stream = plainText + unhexlify(re.sub('0x', '', hex(wepICV)))
     stream = plainText
     
     ## crypt
     seed = self.seedGen(iVal, unhexlify(keyText))
     return rc4(stream, seed), wepICV
Ejemplo n.º 35
0
def WANNA_decrypt(orifile, privkey, out):
    if os.path.exists(orifile) is False:
        return
    newfile = os.path.join(out, os.path.basename(orifile))
    if newfile.endswith('.WannaRen'):
        newfile = newfile[:-9]

    #for big file hang
    with open(orifile, 'rb') as enc_file:
        enc = enc_file.read(11)
        if enc != 'WannaRenkey':
            return

    with open(orifile, 'rb') as enc_file:
        enc = enc_file.read()
    p1 = enc.find('WannaRenkey')
    p2 = enc.find('WannaRen1')
    p3 = enc.find('WannaRen2')

    benc = p1 == 0 and p2 > 0 and p3 > 0
    if benc == False:
        #print "file:%s is not encrypt"%orifile
        return
    print "decrypting %s" % (orifile)
    #rc4 key
    rc4_key = rsa.decrypt(enc[11:267], privkey).decode()

    #rc4 decrypt
    #WannaRen1{data}WannaRen2
    data = enc[p2 + 9:-9]
    res = rc4.rc4(data, rc4_key)

    #save to new file
    #WannaRena{filedata}WannaRenb
    if res.find("WannaRena") < 0 or res.find("WannaRenb") < 0:
        print "decrypt %s failed." % (orifile)

    with open(newfile, 'wb') as n:
        n.write(res[9:-9])
    print "decrypt %s to %s" % (orifile, newfile)
Ejemplo n.º 36
0
    def process_modules(self):
        with open('base.dg', 'rb') as f:
            basesize, = struct.unpack('<I', f.read(4))
            data = f.read()

        dg = Datagram()
        dg.addUint32(len(self.modules) + basesize)
        dg.appendData(data)

        for moduleName in self.modules:
            data, size = self.modules[moduleName]

            dg.addString(moduleName)
            dg.addInt32(size)
            dg.appendData(data)

        data = dg.getMessage()
        compressed = compressString(data, 9)
        key = self.generate_key(100)
        fixed = ''.join(chr((i ^ (5 * i + 7)) % ((i + 6) * 10)) for i in xrange(28))
        rc4.rc4_setkey(key + fixed)
        data = rc4.rc4(compressed)
        return key + data
Ejemplo n.º 37
0
    def process_modules(self):
        with open('base.dg', 'rb') as f:
            basesize, = struct.unpack('<I', f.read(4))
            data = f.read()

        dg = Datagram()
        dg.addUint32(len(self.modules) + basesize)
        dg.appendData(data)

        for moduleName in self.modules:
            data, size = self.modules[moduleName]

            dg.addString(moduleName)
            dg.addInt32(size)
            dg.appendData(data)

        data = dg.getMessage()
        compressed = compressString(data, 9)
        key = self.generate_key(100)
        fixed = ''.join(chr((i ^ (5 * i + 7)) % ((i + 6) * 10)) for i in xrange(28))
        rc4.rc4_setkey(key + fixed)
        data = rc4.rc4(compressed)
        return key + data
Ejemplo n.º 38
0
 def decoder(self, pkt, keyText):
     """Take a packet with [Dot11WEP] and apply RC4 to get the [LLC]
     This function should not need to return fullStream,
     however, because of quirks I've noticed, I return
     fullStream and stream.
     The seed doesn't need to be returned, but why calculate again...
     """
     ## Re-use the IV for comparative purposes
     iVal = pkt[Dot11WEP].iv
     seed = self.seedGen(iVal, unhexlify(keyText))
     
     ## Grab full stream
     fullStream = rc4(pkt[Dot11WEP].wepdata, seed)
     
     ## Prep for removing the 4 icv bytes
     tmp = []
     stream = ''
     for i in range(len(fullStream) - 4):
         tmp.append(fullStream[i])
     for i in tmp:
         stream += i
     
     ## Return the fullstream, stream and iv
     return fullStream, stream, iVal, seed
Ejemplo n.º 39
0
                0xEE,
                0xF7,
                0x01,
                0x79,
                0xBC,
                0x55,
                0x3F,
                0x33,
                0x9E,
                0xB1,
                0xA4,
                0xC1,
                0xAF,
                0x5F,
                0x6A,
                0x54,
                0x7F,
            ),
        },
    ),
]

for name, vectors in TEST_VECTORS:
    print(name, end="")
    entrada = bytearray(vectors["Plain Text"])
    saida = bytearray(vectors["Cipher Text"])
    chave = bytearray(vectors["Key"])
    assert saida == rc4(chave, entrada)
    assert entrada == rc4(chave, saida)
    print(" --> OK")
Ejemplo n.º 40
0
         0xb2, 0x13, 0xf0, 0xed, 0x1a, 0xa7, 0x2f, 0xb8, 0xea, 0x52, 0xb0,
         0xbe, 0x01, 0xcd, 0x1e, 0x41, 0x28, 0x67, 0x72, 0x0b, 0x32, 0x6e,
         0xb3, 0x89, 0xd0, 0x11, 0xbd, 0x70, 0xd8, 0xaf, 0x03, 0x5f, 0xb0,
         0xd8, 0x58, 0x9d, 0xbc, 0xe3, 0xc6, 0x66, 0xf5, 0xea, 0x8d, 0x4c,
         0x79, 0x54, 0xc5, 0x0c, 0x3f, 0x34, 0x0b, 0x04, 0x67, 0xf8, 0x1b,
         0x42, 0x59, 0x61, 0xc1, 0x18, 0x43, 0x07, 0x4d, 0xf6, 0x20, 0xf2,
         0x08, 0x40, 0x4b, 0x39, 0x4c, 0xf9, 0xd3, 0x7f, 0xf5, 0x4b, 0x5f,
         0x1a, 0xd8, 0xf6, 0xea, 0x7d, 0xa3, 0xc5, 0x61, 0xdf, 0xa7, 0x28,
         0x1f, 0x96, 0x44, 0x63, 0xd2, 0xcc, 0x35, 0xa4, 0xd1, 0xb0, 0x34,
         0x90, 0xde, 0xc5, 0x1b, 0x07, 0x11, 0xfb, 0xd6, 0xf5, 0x5f, 0x79,
         0x23, 0x4d, 0x5b, 0x7c, 0x76, 0x66, 0x22, 0xa6, 0x6d, 0xe9, 0x2b,
         0xe9, 0x96, 0x46, 0x1d, 0x5e, 0x4d, 0xc8, 0x78, 0xef, 0x9b, 0xca,
         0x03, 0x05, 0x21, 0xe8, 0x35, 0x1e, 0x4b, 0xae, 0xd2, 0xfd, 0x04,
         0xf9, 0x46, 0x73, 0x68, 0xc4, 0xad, 0x6a, 0xc1, 0x86, 0xd0, 0x82,
         0x45, 0xb2, 0x63, 0xa2, 0x66, 0x6d, 0x1f, 0x6c, 0x54, 0x20, 0xf1,
         0x59, 0x9d, 0xfd, 0x9f, 0x43, 0x89, 0x21, 0xc2, 0xf5, 0xa4, 0x63,
         0x93, 0x8c, 0xe0, 0x98, 0x22, 0x65, 0xee, 0xf7, 0x01, 0x79, 0xbc,
         0x55, 0x3f, 0x33, 0x9e, 0xb1, 0xa4, 0xc1, 0xaf, 0x5f, 0x6a, 0x54,
         0x7f),
    }),
]

for name, vectors in TEST_VECTORS:
    print name,
    entrada = ''.join([chr(n) for n in vectors['Plain Text']])
    saida = ''.join([chr(n) for n in vectors['Cipher Text']])
    chave = ''.join([chr(n) for n in vectors['Key']])
    assert saida == rc4(chave, entrada)
    assert entrada == rc4(chave, saida)
    print 'OK'
Ejemplo n.º 41
0
from panda3d.core import *
import __builtin__, os
import rc4

import niraidata

# Config
prc = niraidata.CONFIG
key, prc = prc[:32], prc[32:]
rc4.rc4_setkey(key)
prc = rc4.rc4(prc)

for line in prc.split('\n'):
    line = line.strip()
    if line:
        loadPrcFileData('nirai config', line)

del prc

# DC
__builtin__.dcStream = StringStream()

dc = niraidata.DC
key, dc = dc[:32], dc[32:]
rc4.rc4_setkey(key)
dc = rc4.rc4(dc)

dcStream.setData(dc)
del dc
rc4.rc4_setkey('\0\0\0\0')
Ejemplo n.º 42
0
def oracle(req):
    key = os.urandom(16)
    cookie = 'QkUgU1VSRSBUTyBEUklOSyBZT1VSIE9WQUxUSU5F'.decode('base64')

    return rc4(key).encrypt(req + cookie)
Ejemplo n.º 43
0
def cifrar(chave, entrada, loops=20):
    vetor_inicial = urandom(10)
    chave = chave + vetor_inicial
    return vetor_inicial + rc4(chave, entrada, loops)
Ejemplo n.º 44
0
def decifrar(chave, entrada, loops=20):
    chave = chave + entrada[:10]
    entrada = entrada[10:]
    return rc4(chave, entrada, loops)
Ejemplo n.º 45
0
def decifrar(senha, octetos):
    ''' Decifrar octetos usando algoritmo RC4 como no Ciphersaber 2 '''
    senha = bytes(senha, CODIF) + octetos[:10]
    octetos = octetos[10:]
    return rc4(senha, octetos, 20)
Ejemplo n.º 46
0
def decifrar(senha, bytes):
    ''' Decifrar bytes usando algoritmo RC4 como no Ciphersaber 2 '''
    senha = senha + bytes[:10]
    bytes = bytes[10:]
    return rc4(senha, bytes, 20)
Ejemplo n.º 47
0
def encrypt(msg):
    return rc4.rc4(map(ord, whatever_key)).encrypt(map(ord, msg))