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)
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)
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)
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()
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
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)
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()
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()
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))
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" )
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()
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()
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))
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]
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
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
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
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")
def encrypt(self, msg): e_start_ts = time.time() start_timestamp = round(time.time(), 5) print('Start timestamp at encryption:', start_timestamp, 's') random.seed(seed_no1) self.sk1 = ''.join(random.choice(possible_chars) for i in range(16)) algo1 = Twofish(self.sk1.encode('utf-8')) encrypt_msg1 = algo1.encrypt(msg.encode('utf-8')) random.seed(seed_no2) self.sk2 = ''.join(random.choice(possible_chars) for i in range(16)) algo2 = Rijndael(self.sk2, self.block_size) encrypt_msg2 = algo2.encrypt(encrypt_msg1 + str(start_timestamp).encode('utf-8')) print('Size of encrypt2:', len(encrypt_msg2), 'bytes') print('\nSize of encrypt1:', len(encrypt_msg1), 'bytes') e_end_ts = time.time() print('Time taken for encrypt():', (e_end_ts - e_start_ts) * 10**3, 'ms') return encrypt_msg2
class TwofishCipher: """ This class handles all the cryptographic operations. """ def __init__(self, key, file_size): self.__cipher = Twofish(key) self.__prev = bytes() self.__file_size = file_size self.__block_count = 0 def encrypt(self, buf): """ Return an encrypted block. """ self.__block_count += block_size # First block, iv generated and prepened to the 1st encrypted block. if not self.__prev: iv = os.urandom(block_size) self.__prev = self.__cipher.encrypt(self.__xor(buf, iv)) return iv + self.__prev # Default blocks. elif (len(buf) == block_size) and (self.__block_count != self.__file_size): self.__prev = self.__cipher.encrypt(self.__xor(buf, self.__prev)) return self.__prev # Last block, add some extra padding. elif len(buf) != block_size: self.__prev = self.__cipher.encrypt(self.__xor(self.__pad(buf), self.__prev)) return self.__prev # Last block equal to 16 bytes, add an extra 16 bytes padding block. elif self.__block_count == self.__file_size: random_block = os.urandom(block_size - 1) + bytes([16]) self.__prev = self.__xor(self.__cipher.decrypt(buf), self.__prev) return self.__prev + random_block def decrypt(self, buf): """ Return a decrypted block. """ self.__block_count += block_size # First block of the file: this is the initialization vector. # Return an empty byte string to maintain compatibility with write(). if not self.__prev: self.__prev = buf return b'' # Decrypt a block. elif self.__block_count != self.__file_size: xored = self.__xor(self.__cipher.decrypt(buf), self.__prev) self.__prev = buf return xored # Decrypt the last block and remove its padding. else: return self.__unpad(self.__xor(self.__cipher.decrypt(buf), self.__prev)) def __pad(self, buf): """ Return a block with padding added (ISO 10126). """ padding = block_size - len(buf) for idx, i in enumerate(range(padding), start=1): buf += os.urandom(1) if idx != padding else bytes([padding]) return buf def __unpad(self, buf): """ Return a block with padding removed (ISO 10126). """ return buf[:-buf[-1]] if buf[:-buf[-1]] else b'' def __xor(self, x, y): """ Return the XOR from two 16bytes blocks. """ x = int.from_bytes(x, byteorder='big') y = int.from_bytes(y, byteorder='big') return (x ^ y).to_bytes(16, byteorder='big')
def twoFish(self, _string): encryptor = Twofish(self.keyGen()) return encryptor.encrypt(pad(_string, 16).encode("utf-8"))
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
def encrypt(password: str) -> bytes: twofish = Twofish(session['password_hash']) encrypted = b'' for chunk in yield_chunks(password.encode('utf-8'), 16): encrypted += twofish.encrypt(chunk) return encrypted
def encrypting(): T = Twofish(b'*secret*') for i in range(len(inputs)): tempencrypted = T.encrypt(inputs[i]) encryptedinput.append(tempencrypted)
def encrypttwofish(importx, filepath, export, expfilepath, inputformat, passwd, raw): if keyimport == 'base64': key = base64.b64decode(passwd) elif keyimport == 'raw': key = passwd elif keyimport == 'base32': key = base64.b32decode(passwd) elif keyimport == 'base16': key = base64.b16decode(passwd) elif keyimport == 'base58': key = base58.b58decode(passwd) elif keyimport == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif keyimport == 'hex': key = passwd.decode('hex') elif keyimport == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif keyimport == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif keyimport == 'binary': key = text_from_bits(passwd) else: print('\033[1;31m[-]\033[0m Unknown error.') return False if importx == 'file': f = open(impfilepath, 'r') raw = f.read() f.close() elif importx == 'print': raw = raw else: print('\033[1;31m[-]\033[0m Unknown error.') return False inp = raw if inputformat == 'base64': iput = base64.b64decode(inp) elif inputformat == 'base32': iput = base64.b32decode(inp) elif inputformat == 'base16': iput = base64.b16decode(inp) elif inputformat == 'base58': iput = base58.b58decode(inp) elif inputformat == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'hex': iput = inp.decode('hex') elif inputformat == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'binary': iput = text_from_bits(inp) else: print('\033[1;31m[-]\033[0m Unknown error.') return False iput = pad(iput) e = Twofish(key) out = e.encrypt(iput) if outputformat == 'base64': output = base64.b64encode(out) elif outputformat == 'raw': output = out elif outputformat == 'base32': output = base64.b32encode(out) elif outputformat == 'base16': output = base64.b16encode(out) elif outputformat == 'base58': output = base58.b58encode(out) elif outputformat == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'hex': output = out.encode('hex') elif outputformat == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'binary': output = text_to_bits(out) else: print('\033[1;31m[-]\033[0m Unknown error.') return False if export == 'file': f = open(outfilepath, 'w') f.write(output) f.close() return True elif export == 'print': return output else: print('\033[1;31m[-]\033[0m Unknown error.') return False
try: os.remove("cloudA.txt") os.remove("cloudB.txt") except OSError: pass K = randhex(256) k2 = split_key(K) print('SECRET KEY PLEASE NOTE DOWN :', K) #print(k2) # 2. E = Apply a one way function to get 128 bit encrypted key output. fake_plain_text_byte = bytes.fromhex(k2[0]) fake_key_text_byte = bytes.fromhex(k2[1]) Twofish_key = Twofish(fake_key_text_byte) E = Twofish_key.encrypt(fake_plain_text_byte) E = E.hex() #print('E: ', E) #print(Twofish_key.decrypt(E).decode()) # 3. P = We get plain Text 128 bits at a time. Plain_Text = input("TYPE PLAIN TEXT TO CIPHER : ") Plain_Text = Plain_Text.encode('utf-8') P = Plain_Text.hex() #print('PLAIN TEXT IN HEX: ',P) #To convert back to string and print #P = bytes.fromhex(Plain_Text); #print(P)