Пример #1
0
	def __init__(self, intercom_id, msg_handler):
		"May raise IndexError exception."
		self.msg_handler = msg_handler
		#This could raise an exception
		(self.name, self.keyString, self.serverAddress, buddies) = intercomDB.lookupAttributes(intercom_id)
		self.id = intercom_id
		self.address = None
		self.buddy_list = [0,0,0]
		self.next_buddy_idx = 0
		for buddy in buddies:
			self.setBuddy(buddy)

		self.next_buddy_idx = 0
		self.encCrypto = xtea.new(self.keyString, mode=ENCRYPTION_MODE, IV="\0"*8)
		self.decCrypto = xtea.new(self.keyString, mode=ENCRYPTION_MODE, IV="\0"*8)
Пример #2
0
def xtea_decrypt_matrix(matrix):
	# whatsgoingonhere
	key = [0x74616877, 0x696F6773, 0x6E6F676E, 0x65726568]
	k = ''.join([pack('>I', x) for x in key])

	m = []

	# convert python matrix
	for i in xrange(3):
		for j in xrange(3):
			m.append(matrix[i][j])

	# last ciphertext block used for validation
	m.append(0x4DE3F9FD)
	# known plaintext last block for validation
	kp = pack('<I', 0x61735320)

	c = ''.join([pack('>I', x) for x in m])
	cipher = xtea.new(k, mode=xtea.MODE_ECB)
	p1 = cipher.decrypt(c)

	# reorder blocks
	blocks = get_blocks(p1, 4)
	p1 = ''.join([b[::-1] for b in blocks])

	# validate plaintext
	if(p1[-len(kp):] == kp):
		return p1
	else:
		return ''
Пример #3
0
def xtea_decrypt_matrix(matrix):
    # whatsgoingonhere
    key = [0x74616877, 0x696F6773, 0x6E6F676E, 0x65726568]
    k = ''.join([pack('>I', x) for x in key])

    m = []

    # convert python matrix
    for i in xrange(3):
        for j in xrange(3):
            m.append(matrix[i][j])

    # last ciphertext block used for validation
    m.append(0x4DE3F9FD)
    # known plaintext last block for validation
    kp = pack('<I', 0x61735320)

    c = ''.join([pack('>I', x) for x in m])
    cipher = xtea.new(k, mode=xtea.MODE_ECB)
    p1 = cipher.decrypt(c)

    # reorder blocks
    blocks = get_blocks(p1, 4)
    p1 = ''.join([b[::-1] for b in blocks])

    # validate plaintext
    if (p1[-len(kp):] == kp):
        return p1
    else:
        return ''
Пример #4
0
def xteaDecrypt(matrix):
    #Establish the key
    key = "tahwiogsnognereh"

    #Take the imported matrix, convert it into a string
    enc_data = ''
    for i0 in xrange(3):
        for i1 in xrange(3):
            #Unpack the matrix entries as four byte Integers in Big Endian
            enc_data += pack('>I', matrix[i0][i1])

    #Because of the check prior to python code running in the shared library we know the last value before decryption should be this
    enc_data += pack('>I', 0x4de3f9fd)

    #Establish the key, and mode for xtea
    enc = xtea.new(key, mode=xtea.MODE_ECB)

    #Decrypt the encrypted data
    decrypted = enc.decrypt(enc_data)
    
    #We have to reformat the decrypted data
    data = ''
    for i in range(0, len(decrypted), 4):
        data += decrypted[i:i+4][::-1]

    #We check to ensure that the last four characters match the four that are appended prior to encryption
    if data[len(data) - 4:len(data)] == " Ssa":
        return data
Пример #5
0
def test_decryption():
    for i in range(len(TEST_VECTORS)):
        vector = TEST_VECTORS[i]
        e = _unwrap(vector['p'])
        c = _unwrap(vector['c'])
        k = _unwrap(vector['k'])

        x = xtea.new(key=k, mode=xtea.MODE_ECB)
        try:
            r = x.decrypt(c)
            assert r == e
        except AssertionError:
            print("Error on test %s:" % i)
            print("Expected %s, got %s!" % (hexlify(e).decode(),
                                            hexlify(r).decode()))
            raise
Пример #6
0
def test_decryption():
    for i in range(len(TEST_VECTORS)):
        vector = TEST_VECTORS[i]
        e = _unwrap(vector['p'])
        c = _unwrap(vector['c'])
        k = _unwrap(vector['k'])

        x = xtea.new(key=k, mode=xtea.MODE_ECB)
        try:
            r = x.decrypt(c)
            assert r == e
        except AssertionError:
            print("Error on test %s:" % i)
            print("Expected %s, got %s!" %
                  (hexlify(e).decode(), hexlify(r).decode()))
            raise
Пример #7
0
def test_decryption():
    """
    Test this xtea implementation against test vectors.
    """
    for i, vector in enumerate(TEST_VECTORS):
        # pylint: disable=invalid-name
        p = _unwrap(vector['p'])
        c = _unwrap(vector['c'])
        k = _unwrap(vector['k'])

        x = xtea.new(key=k, mode=xtea.MODE_ECB)
        try:
            r = x.decrypt(c)
            assert r == p
        except AssertionError:
            print("Error on test %s:" % i)
            print("Expected %s, got %s!" %
                  (hexlify(p).decode(), hexlify(r).decode()))
            raise
Пример #8
0
 def set(self, path, value):
     if not self.controller_online:
         raise protocol_offline('controller offline')
     for retry in range(7):
         try:
             with self.lock:
                 if not hasattr(self.request, 'xtea_key'):
                     use_rsa = True
                 else:
                     use_rsa = False
                 if use_rsa:
                     self.s.settimeout(5)
                     print 'use rsa for xtea set', int(time.time()%3600)
                 else:
                     self.s.settimeout(1.5)
                 #print 'set value', value
                 response = self.make_request(2, path+'='+value, encrypt=True)
                 if response.status == 0:
                     if path == 'misc.xtea_key':
                         self.request.xtea_key = xtea.new(value, mode=xtea.MODE_ECB, IV='\00'*8, rounds=64, endian='!')
                     return 'ok'
                 print 'set error:', response.status
                 raise protocol_error
         except protocol_error:
             if retry >= 1:
                 print 'set retry', retry, int(time.time()%3600)
             if path == 'misc.xtea_key':
                 try:
                     print 'xtea_set uncertain, del key and use rsa', time.time()
                     del self.request.xtea_key
                 except AttributeError:
                     pass
         finally:
             self.s.settimeout(0.5)
         if path == 'misc.xtea_key':
             time.sleep(2)
         else:
             time.sleep(0.2)
     print 'no more set retry'
     raise protocol_error('set %s failed'%path)
Пример #9
0
import xtea

key = "ba9132192c168024076091cce416e50e".decode("hex")

enc = []
plain = []
start = ScreenEA()

# needs to be a multiple of 8
for i in range(24):
    enc.append(chr(Byte(start+i)))
       
x = xtea.new(key, mode=xtea.MODE_ECB)
plain = x.decrypt("".join(enc))

print plain
Пример #10
0
def decrypt(data, root, cm, ckt, ek, cit, ei):
    xtea_mode = {"ECB":xtea.MODE_ECB,
                "CBC":xtea.MODE_CBC,
                "CFB":xtea.MODE_CFB,
                "OFB":xtea.MODE_OFB,
                "CTR":xtea.MODE_CTR}

    mode = cm.get()
    key_type = ckt.get()
    key = ek.get()
    iv_type = cit.get()
    iv = ei.get()

    if key_type == "Hex":
        if re.match("^([0-9A-Fa-f]{2})+$", key):
            key = binascii.a2b_hex(key)
        else:
            tkinter.messagebox.showerror("Error:", message="Key is not in hex format.")
            return
    else:
        key = key.encode()

    if mode in ["CBC", "CFB", "OFB", "CTR"] and iv_type == "Hex":
        if re.match("^([0-9A-Fa-f]{2})+$", iv):
            iv = binascii.a2b_hex(iv)
        else:
            tkinter.messagebox.showerror("Error:", message="IV is not in hex format.")
            return
    else:
        iv = iv.encode()

    if mode in ["CBC", "CFB", "OFB", "CTR"] and len(iv) != xtea.block_size:
        tkinter.messagebox.showerror("Error:", message="IV size must be %d bytes." % xtea.block_size)
        return

    key_length = len(key)
    if key_length != xtea.key_size:
        tkinter.messagebox.showerror("Error:", message="Key size must be %d bytes." % xtea.key_size)
        return

    try:
        if mode == "CFB":
            cipher = xtea.new(key=key, mode=xtea_mode[mode], IV=iv)
        elif mode in ["CBC", "OFB"]:
            cipher = xtea.new(key=key, mode=xtea_mode[mode], IV=iv)
        elif mode == "CTR":
            cipher = xtea.new(key=key, mode=xtea_mode[mode], counter=xtea.Counter(nonce=iv))
        else:
            cipher = xtea.new(key=key, mode=xtea_mode[mode])

        d = cipher.decrypt(data)

        if mode in ["ECB", "CBC"]:
            d = Cryptodome.Util.Padding.unpad(d, xtea.block_size)
    except Exception as e:
        tkinter.messagebox.showerror("Error:", message=e)
        root.quit()
        exit(1) # Not decrypted

    sys.stdout.buffer.write(d)
    root.quit()
    exit(0) # Decrypted successfully
Пример #11
0
c = bytes.decode('hex')

# print disasm(c)

c = map(ord, c)
c = ([0] * 8) + c
c += [0] * (8 - len(c) % 8)

import os
import xtea

pt = ''.join(map(chr, c))

while 1:
    key = '\x00' * 12 + os.urandom(3) + '\x00'
    xt = xtea.new(key, mode=xtea.MODE_ECB, endian='<')
    ct = xt.encrypt(pt)

    if ct.startswith('\x00'):
        break

print '// key : %s' % key.encode('hex')

xtT = xtea.new(key, mode=xtea.MODE_ECB, endian='<')
ptT = xt.decrypt(ct)

assert ptT == pt
assert ptT.startswith('\x00' * 8)
assert len(ct) == len(c)

ct = map(ord, ct)
Пример #12
0
def process_challenge(challenge, password, mode, *args, **kwargs):
    ## XTEA (little endian)
    if mode == 'xtea':
        x = xtea.new(password, mode=xtea.MODE_ECB, endian="<")
        response = x.encrypt(challenge)

    ## XTEA data<->key (little endian)
    if mode == 'xtea data':
        x = xtea.new(challenge, mode=xtea.MODE_ECB, endian="<")
        response = x.encrypt(password)

    ## XTEA (big endian)
    if mode == 'xtea be':
        x = xtea.new(password, mode=xtea.MODE_ECB, endian=">")
        response = x.encrypt(challenge)

    ## XTEA data<->key (big endian)
    if mode == 'xtea be data':
        x = xtea.new(challenge, mode=xtea.MODE_ECB, endian=">")
        response = x.encrypt(password)

    ### TEA (little endian)
    if mode == 'tea':
        t = tea.TinyEncryptionAlgorithm()
        response = str(
            t.encrypt(challenge, password, littleendian=True, padding=False))

    ### TEA data<->key (little endian)
    if mode == 'tea data':
        t = tea.TinyEncryptionAlgorithm()
        response = str(
            t.encrypt(password, challenge, littleendian=True, padding=False))

    ### TEA (big endian)
    if mode == 'tea be':
        t = tea.TinyEncryptionAlgorithm()
        response = str(
            t.encrypt(challenge, password, littleendian=False, padding=False))

    ### TEA data<->key (big endian)
    if mode == 'tea be data':
        t = tea.TinyEncryptionAlgorithm()
        response = str(
            t.encrypt(password, challenge, littleendian=False, padding=False))

    # ### TEA (big endian)
    # if mode == 'tea3':
    #     # response  = "".join(map(chr, tea2.decrypt(list(challenge[:8]), list(password), True)))
    #     # response += "".join(map(chr, tea2.decrypt(list(challenge[8:]), list(password))))
    #     t = tea3.TEA(password)
    #     response = t.decrypt_all(challenge)

    # ### TEA data<->key (big endian)
    # if mode == 'tea3 data':
    #     t = tea3.TEA(challenge)
    #     response = t.decrypt_all(password)

    # ### TEA DATA<->KEY
    # t = tea.TinyEncryptionAlgorithm(*args, **kwargs)
    # response = str(t.encrypt(password, challenge, padding=False))

    # ### MD5
    # md5 = MD5.new()
    # md5.update(challenge)
    # md5.update(password)
    # response = md5.digest()

    # ### HMAC_MD5
    # hmacmd5 = HMAC.new(password, digestmod=MD5)
    # hmacmd5.update(challenge)
    # response = hmacmd5.digest()

    # ### AES-128
    if mode == 'aes':
        aes = AES.new(password, AES.MODE_ECB)
        response = aes.encrypt(challenge)

    # ### AES-128 data<->key
    if mode == 'aes data':
        aes = AES.new(challenge, AES.MODE_ECB)
        response = aes.encrypt(password)

    return response