Example #1
1
def decrypt_PBEWithSHAAndTwofishCBC(encrypted_data, password, salt, iteration_count):
    """
    Decrypts PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
    (Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption of PKCS#12 parameters).
    """
    iv  = derive_key(hashlib.sha1, PURPOSE_IV_MATERIAL,  password, salt, iteration_count, 16)
    key = derive_key(hashlib.sha1, PURPOSE_KEY_MATERIAL, password, salt, iteration_count, 256//8)

    encrypted_data = bytearray(encrypted_data)
    encrypted_data_len = len(encrypted_data)
    if encrypted_data_len % 16 != 0:
        raise BadDataLengthException("encrypted data length is not a multiple of 16 bytes")

    plaintext = bytearray()

    # slow and dirty CBC decrypt
    from twofish import Twofish
    cipher = Twofish(key)

    last_cipher_block = bytearray(iv)
    for block_offset in range(0, encrypted_data_len, 16):
        cipher_block = encrypted_data[block_offset:block_offset+16]
        plaintext_block = xor_bytearrays(bytearray(cipher.decrypt(bytes(cipher_block))), last_cipher_block)
        plaintext.extend(plaintext_block)
        last_cipher_block = cipher_block

    plaintext = strip_pkcs7_padding(plaintext, 16)
    return bytes(plaintext)
Example #2
1
def encrypt_PBEWithSHAAndTwofishCBC(plaintext_data, password, salt, iteration_count):
    """
    Encrypts a value with PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
    (Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption of PKCS#12 parameters).
    """
    iv  = derive_key(hashlib.sha1, PURPOSE_IV_MATERIAL,  password, salt, iteration_count, 16)
    key = derive_key(hashlib.sha1, PURPOSE_KEY_MATERIAL, password, salt, iteration_count, 256//8)

    plaintext_data = add_pkcs7_padding(plaintext_data, 16)
    plaintext_data = bytearray(plaintext_data)
    plaintext_len = len(plaintext_data)
    assert plaintext_len % 16 == 0

    ciphertext = bytearray()

    from twofish import Twofish
    cipher = Twofish(key)

    last_cipher_block = bytearray(iv)
    for block_offset in range(0, plaintext_len, 16):
        plaintext_block = plaintext_data[block_offset:block_offset+16]
        cipher_block = bytearray(cipher.encrypt(bytes(xor_bytearrays(plaintext_block, last_cipher_block))))
        ciphertext.extend(cipher_block)
        last_cipher_block = cipher_block

    return bytes(ciphertext)
Example #3
0
def check_proof(o, proof):
    o = pickle.dumps(o)
    T = Twofish(o[0:32])
    x = T.encrypt(bytes.fromhex(proof))
    if x.hex()[0:3] == '000':
        return True
    return False
Example #4
0
def fencrypt(filen, password, tweak=0, mode='twofish'):
	f=open(filen,'r')
	smstr=f.read()
	f.close()
	if mode=='twofish':
		# splitting it to blocks with 16-bytes len
		if len(smstr)%16:
			nstr=str(smstr+'%'*(16-len(smstr)%16)).encode('utf-8')
		else:
			nstr=smstr.encode('utf-8')

		psswd=Twofish(password)
		encredstr=b'' # ENCRyptED STRing

		# encrypting blocks
		for x in range(int(len(nstr)/16)):
			encredstr+=psswd.encrypt(nstr[x*16:(x+1)*16])

	elif mode=='threefish':
		# splitting it to blocks with 128-bytes len
		if len(smstr)%128:
			nstr=str(smstr+'%'*(128 - len(smstr)%128)).encode('utf-8')
		else:
			nstr=smstr.encode('utf-8')

		psswd=threefish(password,tweak)
		encredstr=b'' # ENCRyptED STRing

		# encrypting blocks
		for x in range(int(len(nstr)/128)):
			encredstr+=psswd.encrypt_block(nstr[x*128:(x+1)*128])
	# writing it to file
	f=open(filen,'wb')
	f.write(encredstr)
	f.close()
Example #5
0
    def decrypt(self, msg):
        d_start_ts = time.time()
        end_timestamp = round(time.time(), 5)
        print('End timestamp at decryption:', end_timestamp, 's')

        random.seed(seed_no2)
        self.sk2 = ''.join(random.choice(possible_chars) for i in range(16))
        algo2 = Rijndael(self.sk2, self.block_size)
        decrypt_msg2 = algo2.decrypt(msg)

        random.seed(seed_no1)
        self.sk1 = ''.join(random.choice(possible_chars) for i in range(16))
        algo1 = Twofish(self.sk1.encode('utf-8'))
        decrypt_msg1 = algo1.decrypt(decrypt_msg2[:16])

        print('Size of decrypt1:', len(decrypt_msg1), 'bytes')
        print('\nSize of decrypt2:', len(decrypt_msg2), 'bytes')

        start_timestamp = float((decrypt_msg2[16:]).decode('utf-8'))
        print('Start timestamp extracted at decryption:', start_timestamp)
        diff_timestamp = end_timestamp - start_timestamp

        d_end_ts = time.time()
        print('Time taken for decrypt():', (d_end_ts - d_start_ts) * 10**3,
              'ms')

        return decrypt_msg1.decode('utf-8'), diff_timestamp
Example #6
0
 def decrypt(self, message, key):
     cipher = Twofish(key)
     data = b''
     for i in range(0, len(message), 16):
         st = message[i:i + 16]
         data += cipher.decrypt(st)
     return data
Example #7
0
def decrypt_PBEWithSHAAndTwofishCBC(encrypted_data, password, salt,
                                    iteration_count):
    """
    Decrypts PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
    (Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption of PKCS#12 parameters).
    """
    iv = derive_key(hashlib.sha1, PURPOSE_IV_MATERIAL, password, salt,
                    iteration_count, 16)
    key = derive_key(hashlib.sha1, PURPOSE_KEY_MATERIAL, password, salt,
                     iteration_count, 256 // 8)

    encrypted_data = bytearray(encrypted_data)
    encrypted_data_len = len(encrypted_data)
    if encrypted_data_len % 16 != 0:
        raise BadDataLengthException(
            "encrypted data length is not a multiple of 16 bytes")

    plaintext = bytearray()

    # slow and dirty CBC decrypt
    from twofish import Twofish
    cipher = Twofish(key)

    last_cipher_block = bytearray(iv)
    for block_offset in range(0, encrypted_data_len, 16):
        cipher_block = encrypted_data[block_offset:block_offset + 16]
        plaintext_block = xor_bytearrays(
            bytearray(cipher.decrypt(bytes(cipher_block))), last_cipher_block)
        plaintext.extend(plaintext_block)
        last_cipher_block = cipher_block

    plaintext = strip_pkcs7_padding(plaintext, 16)
    return bytes(plaintext)
Example #8
0
def encrypt_PBEWithSHAAndTwofishCBC(plaintext_data, password, salt,
                                    iteration_count):
    """
    Encrypts a value with PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
    (Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption of PKCS#12 parameters).
    """
    iv = derive_key(hashlib.sha1, PURPOSE_IV_MATERIAL, password, salt,
                    iteration_count, 16)
    key = derive_key(hashlib.sha1, PURPOSE_KEY_MATERIAL, password, salt,
                     iteration_count, 256 // 8)

    plaintext_data = add_pkcs7_padding(plaintext_data, 16)
    plaintext_data = bytearray(plaintext_data)
    plaintext_len = len(plaintext_data)
    assert plaintext_len % 16 == 0

    ciphertext = bytearray()

    from twofish import Twofish
    cipher = Twofish(key)

    last_cipher_block = bytearray(iv)
    for block_offset in range(0, plaintext_len, 16):
        plaintext_block = plaintext_data[block_offset:block_offset + 16]
        cipher_block = bytearray(
            cipher.encrypt(
                bytes(xor_bytearrays(plaintext_block, last_cipher_block))))
        ciphertext.extend(cipher_block)
        last_cipher_block = cipher_block

    return bytes(ciphertext)
Example #9
0
class TwofishCipher:
    """ This class handles all the cryptographic operations. """
    def __init__(self, key):
        self.__bs = bs
        self.__cipher = Twofish(key)

    def __add_pad(self, chunk):
        """ Return a chunk with padding added (ISO 10126). """
        padding = self.__bs - len(chunk)
        for idx, i in enumerate(range(padding), start=1):
            chunk += os.urandom(1) if idx != padding else bytes([padding])
        return chunk

    def __del_pad(self, chunk):
        """ Return a chunk with padding removed (ISO 10126). """
        return chunk[:-chunk[-1]]

    def encrypt(self, chunk):
        """ Return an encrypted chunk. """
        if len(chunk) != bs:
            return self.__cipher.encrypt(self.__add_pad(chunk))
        else:
            return self.__cipher.encrypt(chunk)

    def decrypt(self, chunk, unpad=False):
        """ Return a decrypted chunk. """
        if unpad:
            return self.__del_pad(self.__cipher.decrypt(chunk))
        else:
            return self.__cipher.decrypt(chunk)
Example #10
0
 def __init__(self, key, iv):
     self.log = logging.getLogger("twofish.cbc.%s" % type(self).__name__)
     self.log.debug('initing')
     assert len(iv) == 16
     from twofish import Twofish
     self.key = key
     self.iv = iv
     self.tw = Twofish(self.key)
Example #11
0
def find_nonce(o):
    T = Twofish(o[0:32])
    x = secrets.token_bytes(16)
    secret = secrets.token_bytes(16)
    while x.hex()[0:3] != '000':
        secret = secrets.token_bytes(16)
        x = T.encrypt(secret)

    return secret.hex(), x.hex()
Example #12
0
 def encrypt(self, message, key):
     cipher = Twofish(key)
     data = b''
     for i in range(0, len(message), 16):
         st = message[i:i + 16]
         if len(st) < 16:
             st = st + b' ' * (16 - len(st))
         data += cipher.encrypt(st)
     return self.encryption.encrypt(data, key)
Example #13
0
def produceCCMtag(nonce, payload, header, key=None):
    if (key == None):
        raise AttributeError("CCMtag key undefined")
    iv = Twofish(key).encrypt(produceIV(nonce, len(payload)))
    processed_header = blockCipherZeroPad(produceHeaderHeader(header))
    result = (CBCMode(Twofish(key), iv).encrypt(processed_header + blockCipherZeroPad(payload)))
    result = result[len(result) - 16:len(result) - 8]  # mac
    ctr = Twofish(key).encrypt(produceCTRblock(nonce, 0))
    final = stringXOR(result, ctr)
    return final
Example #14
0
def fdecrypt(filen,password):
    f=open(filen,'rb')
    smstr=f.read()
    f.close()
    psswd=Twofish(password)
    decredstr=b''

    for x in range(int(len(smstr)/16)):
        decredstr+=psswd.decrypt(smstr[x*16:(x+1)*16])

    return codecs.decode(decredstr,'utf-8').strip('%')
Example #15
0
def TWOde(key, in_filename, out_filename=None, chunksize=16):
    key = key.encode('utf-8')
    key = Twofish(key)
    if not out_filename:
        out_filename = in_filename[:-4]
    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                outfile.write(key.decrypt(chunk))
Example #16
0
def whale(key , cipher):
	#Define key:
	#key = str(raw_input("Key:	"))
	#cipher = str(raw_input("Cipher:	   "))

	#Get key:

	try:
		tuna = Twofish(key)
		print(key + ": " + tuna.decrypt(cipher).decode())
	except:
		#print("Key :" + key + " failed")
		pass; # save your eye some trouble
Example #17
0
def whale(key, cipher):
    #Define key:
    #key = str(raw_input("Key:	"))
    #cipher = str(raw_input("Cipher:	   "))

    #Get key:

    try:
        tuna = Twofish(key)
        print(key + ": " + tuna.decrypt(cipher).decode())
    except:
        #print("Key :" + key + " failed")
        pass
Example #18
0
class TwofishExample:
    """
    A class to represent an TwofishExample.

    METHODS
    -------
    encrypt(msg):
        Encrypts the msg and returns it.

    decrypt(encrypted):
        Decrypts the encrypted msg and returns it.
    """
    def __init__(self):
        """
        Constructs the TwofishExample object.
        """
        self.key = b'FSMF73R873YM1872Y'
        self.tf = Twofish(self.key)

    def encrypt(self, msg):
        """
        Encrypts the msg.

        PARAMETERS
        ----------
        :param msg : Message to be encrypted
        :type msg : str

        RETURNS
        -------
        :returns encrypted message
        :rtype bytearray
        """
        return self.tf.encrypt(msg)

    def decrypt(self, encrypted):
        """
        Decrypts the encrypted message.

        PARAMETERS
        ----------
        :param encrypted : Encrypted message to be decrypted
        :type encrypted : bytearray

        RETURNS
        -------
        :returns decrypted message
        :rtype str
        """
        return self.tf.decrypt(encrypted).decode()
Example #19
0
def twofish_decrypt(password, path):
    infile = open(path, "rb")
    data = infile.read()
    infile.close()

    cipher = Twofish(bytes(password, 'utf-8'))
    decrypted = b''  # decrypted string

    for x in range(int(len(data) / 16)):
        decrypted += cipher.decrypt(data[x * 16:(x + 1) * 16])

    outfile = open(path + '.decrypted', "wb")
    outfile.write(decrypted)
    outfile.close()
Example #20
0
def TWOen(key, in_filename, out_filename=None, chunksize=16) :
	key = key.encode('utf-8')
	key = Twofish(key)
	if not out_filename :
		out_filename = in_filename + '.enc'
	with open(in_filename, 'rb') as infile :
		with open(out_filename, 'wb') as outfile :
			while True :
				chunk = infile.read(chunksize)
				if len(chunk) == 0:
					break
				elif len(chunk) % 16 != 0 :
					temp = ' '*(16 - len(chunk)%16)
					chunk += temp.encode('utf-8')
				outfile.write(key.encrypt(chunk))
Example #21
0
    def test_ecb(self):
        from twofish import Twofish

        tw = Twofish(self.key)
        for testData in self.testData:
            self.assertTrue(
                len(testData) % 16 == 0, "Test data length needs to be evenly divisible by 16. Got %r" % len(testData)
            )
            # Can take multiple blocks
            cipherText = tw.encrypt(testData)
            self.assertNotEqual(cipherText, testData, "Plain and cipher text should not be the same")
            decrypted = tw.decrypt(cipherText)
            self.assertEqual(
                decrypted, testData, "The encrypted and then decrypted text should match the original text"
            )
Example #22
0
class TwofishCBCDecryption(object):
    def __init__(self, key, iv):
        self.log = logging.getLogger("twofish.cbc.%s" % type(self).__name__)
        self.log.debug('initing')
        assert len(iv) == 16
        from twofish import Twofish
        self.key = key
        self.iv = iv
        self.tw = Twofish(self.key)

    def decrypt(self, blocks):
        assert len(
            blocks
        ) % 16 == 0, "Expected cipher text length to be a multiple of 16. Got %r. " % len(
            blocks)
        ret = b''
        while len(blocks) > 0:
            block = blocks[:16]
            blocks = blocks[16:]
            ret += self.decryptBlock(block)
        return ret

    def decryptBlock(self, block):
        assert len(block) == 16
        intr = self.tw.decrypt(block)
        oldIV = self.iv
        self.iv = block
        return xor(oldIV, intr)
Example #23
0
def CTRmodeEncryptData(plain, nonce, key):
    if (key is None): return None
    padded = blockCipherZeroPad(plain)
    stream = ''
    for i in range(len(padded) >> 4):
        stream += Twofish(key).encrypt(produceCTRblock(nonce, i + 1))
    return stringXOR(padded, stream)[:len(plain)]
Example #24
0
 def __init__(self, keylen, time_str, state, algorythm):
     if keylen != 16 and keylen != 24 and keylen != 32:
         keylen = 16  # Either keying 1 or 2, resp.
     self.IV = Random.new().read(state)  #Init vector
     self.key = Random.new().read(keylen)
     self.__state = Random.new().read(state)
     self.__time_format = time_str
     if algorythm == 'DES':
         self.cipher = DES3.new(self.key, DES3.MODE_CBC, self.IV)
     if algorythm == 'AES':
         self.cipher = AES.new(self.key, AES.MODE_CBC, self.IV)
     if algorythm == 'CAST':
         self.cipher = CAST.new(self.key, CAST.MODE_CBC, self.IV)
     if algorythm == 'BLOWFISH':
         self.cipher = Blowfish.new(self.key, Blowfish.MODE_CBC, self.IV)
     if algorythm == 'Twofish':
         self.cipher = Twofish(self.key)
     if algorythm == "RC2":
         self.cipher = ARC2.new(self.key, ARC2.MODE_CBC, self.IV)
     if algorythm == "IDEA":
         self.cipher = IDEA(self.key)
     if algorythm == "RC5":
         self.cipher = RC5(self.key, BLOCKSIZE, ROUNDS)
     if algorythm == "GOST28147":
         self.IV = Random.new().read(8)
         self.cipher = "gost"
Example #25
0
class TwofishCBCDecryption(object):
    def __init__(self, key, iv):
        self.log = logging.getLogger("twofish.cbc.%s" % type(self).__name__)
        self.log.debug('initing')
        assert len(iv) == 16
        from twofish import Twofish
        self.key = key
        self.iv = iv
        self.tw = Twofish(self.key)

    def decrypt(self, blocks):
        assert len(blocks) % 16 == 0, "Expected cipher text length to be a multiple of 16. Got %r. " % len(blocks)
        ret = ''
        while len(blocks) > 0:
            block = blocks[:16]
            blocks = blocks[16:]
            ret += self.decryptBlock(block)
        return ret

    def decryptBlock(self, block):
        assert len(block) == 16
        intr = self.tw.decrypt(block)
        oldIV = self.iv
        self.iv = block
        return xor(oldIV, intr)
Example #26
0
 def send(self):
     to_send=self.entry.get()
     print("Sending: "+to_send)
     index=random.randrange(1,100,1)
     key=self.alldata.key[index]
     self.alldata.encrypt_key=key
     self.setkeylabel()
     tfh=Twofish(key.encode())
     if(self.alldata.encrypt_key==""):
         #self.send_queue.put("message "+to_send)
         self.alldata.senddict[self.messenger_socket].put("message "+to_send)
         self.alldata.sent_raw_message[self.messenger_socket].put("message "+to_send)
         self.alldata.outputs.append(self.messenger_socket)
     else:
         try:
             encrypted_data=self.alldata.encryptor.encode(to_send,tfh)
         except LookupError:
             self.alldata.encryptor=Encryptor(b'7774')
             encrypted_data=self.alldata.encryptor.encode(to_send, tfh)
             
         msg_data = tools.message_obj(index, encrypted_data, None)
         self.alldata.senddict[self.messenger_socket].put(pickle.dumps(msg_data))
         self.alldata.sent_raw_message[self.messenger_socket].put(str(index).encode() + b' ' + encrypted_data)
         self.alldata.outputs.append(self.messenger_socket)
     
     self.messagequeue.put(datetime.date.strftime(datetime.datetime.now(),'%m/%d-%H:%M:%S')+"\nME: "+to_send)
     self.entry.delete(0,'end')
Example #27
0
 def __init__(self, key, iv):
     self.log = logging.getLogger("twofish.cbc.%s" % type(self).__name__)
     self.log.debug('initing')
     assert len(iv) == 16
     from twofish import Twofish
     self.key = key
     self.iv = iv
     self.tw = Twofish(self.key)
Example #28
0
def fencrypt(filen,password):
    f=open(filen,'r')
    smstr=f.read()
    f.close()
    if len(smstr)%16:
        nstr=str(smstr+'%'*(16-len(smstr)%16)).encode('utf-8')
    else:
        nstr=smstr.encode('utf-8')

    psswd=Twofish(password)
    encredstr=b''

    for x in range(int(len(nstr)/16)):
        encredstr+=psswd.encrypt(nstr[x*16:(x+1)*16])

    f=open(filen,'wb')
    f.write(encredstr)
    f.close()
Example #29
0
def TWOde(key, in_filename, out_filename=None, chunksize=16) :
	key = key.encode('utf-8')
	key = Twofish(key)
	if not out_filename :
		out_filename = in_filename[:-4]
	with open(in_filename, 'rb') as infile :
		with open(out_filename, 'wb') as outfile :
			while True :
				chunk = infile.read(chunksize)
				if len(chunk) == 0 :
					break 
				outfile.write(key.decrypt(chunk))


# key = 'pass'

# TWOen(key, 'Capture.PNG')
# TWOde(key, 'Capture.PNG.enc', 'random.png')
Example #30
0
 def twofishEncrypt():
     start_time = time()
     key = twofish_password.get()
     T = Twofish(key)
     n = 16
     pos = 0
     x = []
     res = ""
     for c in normal_message:
         if (pos % n == 0):
             if (pos == 0):
                 res += c
             else:
                 x.append(res)
                 res = ""
                 res += c
         else:
             res += c
         pos = pos + 1
     print(x)
     carry = res
     i = 0
     msg_len = 16 - len(carry)
     while i < msg_len:
         carry += "_"
         i = i + 1
     x.append(carry)
     twofish_array = []
     for split_message in x:
         print("split normal message : " + split_message)
         cipher_twofish = T.encrypt(split_message)
         print("split cipher result : " + cipher_twofish.encode("hex"))
         cipher_twofish = cipher_twofish.encode("hex")
         twofish_array.append(cipher_twofish)
     global twofish_encrypted_message
     twofish_encrypted_message = "".join(twofish_array)
     print("merged cipher result : " + twofish_encrypted_message)
     messagebox.showinfo("Success", "Encrypt Twofish Success")
     end_time = time()
     time_taken = end_time - start_time
     hours, rest = divmod(time_taken, 3600)
     minutes, seconds = divmod(rest, 60)
     print("Time taken:", format_timespan(end_time - start_time))
Example #31
0
def twofish_encrypt(password, path):
    infile = open(path, "r")
    data = infile.read()
    infile.close()

    if len(data) % 16:
        nstr = str(data + "%" * (16 - len(data) % 16)).encode('ascii')
    else:
        nstr = data.encode("ascii")

    cipher = Twofish(bytes(password, 'ascii'))
    encrypted = b''

    for x in range(int(len(nstr) / 16)):
        encrypted += bytes(cipher.encrypt(nstr[x * 16:(x + 1) * 16]))

    outfile = open(path + '.encrypted', "wb")
    outfile.write(encrypted)
    outfile.close()
Example #32
0
class TwoFish:
    def __init__(self, key=None):
        if key is None: self.key = secrets.token_bytes(16)
        else: self.key = key
        self.tf = Twofish(self.key)

    def encode(self, strs):
        strs = _16fillblock(strs)
        ret = b''
        for i in range(len(strs)):
            ret += self.tf.encrypt(strs[i])
        return ret

    def decode(self, strs):
        strs = _16fillblock(strs)
        ret = b''
        for i in range(len(strs)):
            ret += self.tf.decrypt(strs[i])
        return ret[:len(ret) - 16]
Example #33
0
    def encrypt(self, msg):
        e_start_ts = time.time()
        start_timestamp = round(time.time(), 5)
        print('Start timestamp at encryption:', start_timestamp, 's')

        algo1 = Twofish(self.sk.encode('utf-8'))
        encrypt_msg1 = algo1.encrypt(msg.encode('utf-8'))

        algo2 = Rijndael(self.sk, self.block_size)
        encrypt_msg2 = algo2.encrypt(encrypt_msg1 +
                                     str(start_timestamp).encode('utf-8'))

        print('\nSize of encrypt1:', len(encrypt_msg1), 'bytes')
        print('Size of encrypt2:', len(encrypt_msg2), 'bytes')

        e_end_ts = time.time()
        print('Time taken for encrypt():', (e_end_ts - e_start_ts) * 10**3,
              'ms')

        return encrypt_msg2
Example #34
0
def TwofishEncryption(key, msgB):
    encrypted = ""
    i = 0

    #start encrypt
    start = time.perf_counter()
    loops = math.ceil(len(msgB) / 16)
    T = Twofish(key[:32].encode("UTF-8"))
    while i < loops:
        x = T.encrypt(msgB[i:i + 16])
        x = binascii.hexlify(x)
        x = x.decode("UTF-8")
        encrypted += x
        i += 1
    stop = time.perf_counter()
    #encrypt stop

    #stats begining
    lenght = len(encrypted)
    timeDiff = stop - start
    return lenght, timeDiff
Example #35
0
 def twofishDecrypt():
     # twf_var.get() #ini get password
     start_time = time()
     global decrypt_twofish_join
     text = hc_join
     key = twofish_password.get()
     T = Twofish(key)
     n = 32
     ii = 0
     x = []
     res = ""
     for c in text:
         if (ii % n == 0):
             if (ii == 0):
                 res += c
             else:
                 x.append(res)
                 res = ""
                 res += c
         else:
             res += c
         ii = ii + 1
     x.append(res)
     print(x)
     twofish_array = []
     for twofish_plain_res in x:
         print(twofish_plain_res)
         twofish_decrypt = T.decrypt(twofish_plain_res.decode("hex"))
         print(twofish_decrypt)
         twofish_array.append(twofish_decrypt)
     decrypt_twofish_join = "".join(twofish_array)
     print(decrypt_twofish_join)
     messagebox.showinfo("Success", "Decrypt Twofish Success")
     end_time = time()
     time_taken = end_time - start_time
     hours, rest = divmod(time_taken, 3600)
     minutes, seconds = divmod(rest, 60)
     print("Time taken:", format_timespan(end_time - start_time))
Example #36
0
    def decrypt(self, msg):
        d_start_ts = time.time()
        end_timestamp = round(time.time(), 5)
        print('End timestamp at decryption:', end_timestamp, 's')

        algo2 = Rijndael(self.sk, self.block_size)
        decrypt_msg2 = algo2.decrypt(msg)

        algo1 = Twofish(self.sk.encode('utf-8'))
        decrypt_msg1 = algo1.decrypt(decrypt_msg2[:16])

        print('\nSize of decrypt2:', len(decrypt_msg2), 'bytes')
        print('Size of decrypt1:', len(decrypt_msg1), 'bytes')

        start_timestamp = float((decrypt_msg2[16:]).decode('utf-8'))
        print('Start timestamp extracted at decryption:', start_timestamp, 's')
        diff_timestamp = end_timestamp - start_timestamp

        d_end_ts = time.time()
        print('Time taken for decrypt():', (d_end_ts - d_start_ts) * 10**3,
              'ms')

        return decrypt_msg1.decode('utf-8'), diff_timestamp
Example #37
0
def index():
    if request.method == 'POST':
        gener_key = generator2()
        T = Twofish(gener_key)
        plaintext = request.form['plaintext']
        plaintext_original = request.form['plaintext']
        if (len(plaintext) < 16):
            while (len(plaintext) < 16):
                plaintext = plaintext + random.choice(string.ascii_letters)
        if (len(plaintext) == 16):
            chipertext = T.encrypt(bytes(plaintext, 'utf-8'))
            new_chipertext = Ciphertext(chipertext, gener_key)
            #new_key = Ciphertext(hex_to_binary(gener_key))
            #db.session().add(new_chipertext)
            db.session().add(new_chipertext)
            db.session().commit()
            result = chipertext.decode('utf-8', 'ignore')
            #chipertext_to_plaintext = T.decrypt(chipertext)
            return render_template("index.html",
                                   result_c=result,
                                   result_p=plaintext_original)

    return render_template("index.html")
Example #38
0
def fdecrypt(filen, password, tweak=0, mode='twofish'):
	# reading file in byte mode
	f=open(filen,'rb')
	smstr=f.read()
	f.close()

	if mode=='twofish':
		psswd=Twofish(password)
		decredstr=b''

		# decrypting blocks
		for x in range(int(len(smstr)/16)):
			decredstr+=psswd.decrypt(smstr[x*16:(x+1)*16])

	elif mode=='threefish':

		psswd=threefish(password,tweak)
		decredstr=b''

		# decrypting blocks
		for x in range(int(len(smstr)/128)):
			decredstr+=psswd.decrypt_block(smstr[x*128:(x+1)*128])

	return decode(decredstr,'utf-8').strip('%')
Example #39
0
class TwofishCBCEncryption(object):
    def __init__(self, key, iv):
        self.log = logging.getLogger("twofish.cbc.%s" % type(self).__name__)
        self.log.debug('initing')
        assert len(iv) == 16
        from twofish import Twofish
        self.key = key
        self.iv = iv
        self.tw = Twofish(self.key)

    def encrypt(self, blocks):
        assert len(blocks) % 16 == 0
        ret = ''
        while len(blocks) > 0:
            block = blocks[:16]
            blocks = blocks[16:]
            ret += self.encryptBlock(block)
        return ret

    def encryptBlock(self, block):
        assert len(block) == 16
        self.iv = self.tw.encrypt(xor(self.iv, block))
        return self.iv
Example #40
0
def CBC_encrypt(IV_str: str, key_str: str, data_str: str) -> str:
    '''
    Encrypt data CBC using the IV, key and the actual data

    IV - Initialization Value (aka the salt/nonce) (what type?)
    key - the key (what type?)
    data - the data (what type?)
    '''
    print('[*] Encrypting database...')

    IV = IV_str.encode('utf-8')
    key = key_str.encode('utf-8')
    data = data_str.encode('utf-8')
    
    if len(IV) > 16:
        while len(IV) != 16:
            IV = IV[1:]
    if len(IV) < 16:
        while len(IV) != 16:
            for i in IV:
                IV += i
                if len(IV) == 16:
                    break
    if len(key) > 32:
        while len(key) != 32:
            key = key[1:]
    cipher = Twofish(key)
    rounds = int(float(len(data))/16)
    #print("[+] Initiating encryption process..")

    buf = b''
    block = data[:16]
    data = data[16:]
    if len(block) != 16:
        block = padup(block)
    #print('block: {}\niv: {}'.format(len(block), len(IV)))
    # hexxed is type(bytes)
    hexxed = byte_hexxor(block, IV)
    #print('hexxed: {}\nlen: {}'.format(hexxed, len(hexxed)))
    # block is type(bytes)
    block = cipher.encrypt(hexxed)

    buf += block

    for round in range(0, rounds-1):
        data_chunk_bytes = data[:16]
        hexxed = byte_hexxor(data_chunk_bytes, block)
        #print(type(hexxed))
        #print(len(hexxed))
        block = cipher.encrypt(hexxed)
        #print('data: {}'.format(base64.b64encode(hexxed)))
        #print('block : {}'.format(base64.b64encode(block)))
        buf += block
        data = data[16:]
        #print(type(data))
        
        if len(data) < 16: # Padding up the last block.
            data = padup(data)  # data is bytes
            block = cipher.encrypt(byte_hexxor(data, block))
            buf += block
            break
    
    # Obfuscation for the 0END signature.
    #print("buf " + str(base64.b64encode(buf)))
    #print(data)
    data = ASCII_0END_BLOCK[:]  # Make a copy of the block
    block = cipher.encrypt(byte_hexxor(data, block))
    buf += block
    #print('buf: ', end='')
    #print(base64.b64encode(buf))
    #print('=======================')
    for i in range(rand(1,obfuscation_layers)):
        if rand(1, 3301) % 2 == 0:
            data = ASCII_0END_BLOCK[:]
        else:
            data = padup("")
        block = cipher.encrypt(byte_hexxor(data, block))
        buf += block
        
    
    if padding != 0:
        buf = b"PADDING = " + str(padding).encode('utf-8') + b"\n" + buf
    print('[*] Database encrypted.')
    return buf
Example #41
0
def CBC_decrypt(IV_str, key_str, data): 
    '''
    Decrypt a Twofish-CBC encrypted file.

    IV - Initalization Vector (aka nonce)
    key - The key used to decrypt the file (type str)
    data - the file to be decrypted (type str)
    '''
    print('[*] Decrypting database...')

    IV = IV_str.encode('utf-8')
    key = key_str.encode('utf-8')

    assert type(data) == bytes

    if len(IV) > 16:
        #while len(IV) != 16:
        #    IV = IV[1:]
        IV = IV[len(IV)-16:]
    elif len(IV) < 16:  # TODO: How to do this better?
        copy = IV[:]
        while len(IV) != 16:
            for i in copy:
                IV += i
                if len(IV) == 16:
                    break

    assert len(IV) == 16
    
    # keysize is limited to 32 bytes as per libtwofish, the libary
    # that pytwofish is based off of
    if len(key) > 32:
        while len(key) != 32:
            key = key[1:]

    #print(len(key))
    cipher = Twofish(key)

    padlen = 0
    if b'PADDING' in data:
        data = data.replace(b'PADDING = ', b'')
        padlen = int(data[:data.find(b'\n')])
        data = data[data.find(b'\n')+1:]


    # number or rounds is equal the the number of 16-byte blocks
    rounds = len(data) // 16
    #print('padding length: {}'.format(padlen))
    #print('data length: {}'.format(len(data)))
    #print('[+] Initiating decryption process..')

    buf = b''

    old_block = data[:16]
    #print('old block: {}'.format(len(old_block)))
    data = data[16:]
    #print('old_block len: {}'.format(len(old_block)))
    hexxed = byte_hexxor(cipher.decrypt(old_block), IV)
    new_block = byte_hexxor(cipher.decrypt(old_block), IV)
    buf += new_block

    assert type(new_block) == bytes and type(old_block) == bytes

    for rnd in range(rounds-1):
        new_block = data[:16]
        data = data[16:]
        #print('old: {}\nnew: {}'.format(base64.b64encode(old_block), base64.b64encode(new_block)))
        #print('='*5)
        buf += byte_hexxor(cipher.decrypt(new_block), old_block)
        old_block = new_block[:]

    # strip obfuscation
    end_block_index = buf.find(ASCII_0END_BLOCK)  # USE find() here, rfind() breaks sutff
    if end_block_index != -1:
        buf = buf[:end_block_index]

    # strip padding
    if padlen != 0:
        buf = buf[:len(buf)-padlen]

    print('[*] Database decrypted.')
    return buf
Example #42
-1
from twofish import Twofish
import sys

T = Twofish(sys.argv[1])
crypt = raw_input('encrypted data: ')

print 'decrypted:'
i = 0
while (i < len(crypt)):
	sys.stdout.write(T.decrypt(crypt[i:i+16]))
	i+=16