Exemplo n.º 1
0
 def __init__(self, fp, key):
     self._fp = fp
     header = Header.from_file(fp)
     if header.tag != self.TAG:
         raise NotPwsafeV3('invalid tag "%s"' % header.tag)
     p1 = self.stretch_key(key, header.salt, header.iterations)
     if not hmac.compare_digest(hashlib.sha256(p1).digest(), header.hp1):
         raise InvalidPassword()
     ff = twofish.Twofish(p1)
     K = ff.decrypt(header.b1) + ff.decrypt(header.b2)
     L = ff.decrypt(header.b3) + ff.decrypt(header.b4)
     self._hmac = hmac.new(L, digestmod=self.DIGESTMOD)
     self._fishfish = twofish.Twofish(K)
     self._iv = header.iv
Exemplo n.º 2
0
def write_params(sheet1, params, i):

    text = params[1]
    key = params[2]
    enc_dec = params[3]
    result = params[4]
    twofish_SW = twofish.Twofish(key)
    expected_enc_value = twofish_SW.encrypt(text)
    expected_dec_value = twofish_SW.decrypt(text)
    print("*************************")
    print(hex(result))
    print(hex(expected_enc_value))
    print(hex(expected_dec_value))
    print("*************************")
    error = 0
    if (enc_dec):
        if (expected_dec_value != result):
            error = 1
    else:
        if (expected_enc_value != result):
            error = 1

    sheet1.write(i, 1, hex(text))
    sheet1.write(i, 2, hex(key))
    sheet1.write(i, 3, hex(enc_dec))
    sheet1.write(i, 4, hex(result))
    sheet1.write(i, 5, hex(expected_enc_value))
    sheet1.write(i, 6, hex(expected_dec_value))
    sheet1.write(i, 7, hex(error))

    return i + 1
Exemplo n.º 3
0
def create_microsd_vectors(micro_sd,storage_file,N,e):
    storage_file.seek(0)
    #storage_file.write(int(N).to_bytes(4,byteorder='big'))
    zero = 0
    counter_errors = 0
    j=0
    for i in range(0,N):
        

        key = np.random.randint(0,2**63-1,1,dtype=np.int64)
        text = np.random.randint(0,2**63-1,1,dtype=np.int64)
        twofish_SW = twofish.Twofish(int(key[0]))
        expected_enc_value = twofish_SW.encrypt(int(text[0]))
        expected_dec_value = twofish_SW.decrypt(int(text[0]))

        percent = random.randint(1,100)
        if(percent < e):
            expected_enc_value = expected_enc_value + 1
            expected_dec_value = expected_dec_value + 1
            counter_errors = counter_errors + 1

        storage_file.write(int(key[0]).to_bytes(16, byteorder='little'))   
        storage_file.write(int(text[0]).to_bytes(16, byteorder='little'))   
        storage_file.write(expected_enc_value.to_bytes(16, byteorder='little'))   
        storage_file.write(expected_dec_value.to_bytes(16, byteorder='little'))    


        #clear block
        micro_sd.seek(BLOCK_SIZE*(NUM_BLOCK_TEST+j))
        micro_sd.write(zero.to_bytes(512, byteorder='big'))

        micro_sd.seek(BLOCK_SIZE*(NUM_BLOCK_TEST+j))
        j=j+1
        micro_sd.write(SIGNATURE.to_bytes(4, byteorder='big'))
        micro_sd.write(int(text[0]).to_bytes(16, byteorder='little'))
        micro_sd.write(int(key[0]).to_bytes(16, byteorder='little'))
        micro_sd.write(int(0).to_bytes(1, byteorder='little'))#enc
        micro_sd.write(int(expected_enc_value).to_bytes(16,byteorder='little'))

        #clear block
        micro_sd.seek(BLOCK_SIZE*(NUM_BLOCK_TEST+j))
        micro_sd.write(zero.to_bytes(512, byteorder='big'))


        micro_sd.seek(BLOCK_SIZE*(NUM_BLOCK_TEST+j))
        j = j+1
        micro_sd.write(SIGNATURE.to_bytes(4, byteorder='big'))
        micro_sd.write(int(text[0]).to_bytes(16, byteorder='little'))
        micro_sd.write(int(key[0]).to_bytes(16, byteorder='little'))
        micro_sd.write(int(1).to_bytes(1, byteorder='little'))#enc
        micro_sd.write(int(expected_dec_value).to_bytes(16,byteorder='little'))


        #clear block
        micro_sd.seek(BLOCK_SIZE*(NUM_BLOCK_TEST+j))
        micro_sd.write(zero.to_bytes(512, byteorder='big'))



    return counter_errors
Exemplo n.º 4
0
 def __init__(self, key, init_vec=0):
     """
     Set the key to be used for en-/de-cryption and optionally specify an initialization vector (aka seed/salt).
     """
     self.twofish = twofish.Twofish()
     self.twofish.set_key(key)
     self.state = init_vec
Exemplo n.º 5
0
    def encrypt(cls, data, key):
        validate_key_size(key, cls.key_size, "Twofish")

        iv, ctr = BlockCipher.generate_encrypt_iv_counter(cls.block_size)
        tfish = twofish.Twofish(key)
        ciphertext = strxor(data, cls._gen_keystream(len(data), tfish, ctr))

        return iv + ciphertext
Exemplo n.º 6
0
    def encrypt(cls, data, key, iv_data):
        validate_key_size(key, cls.key_size, "Twofish")

        iv, ctr = iv_data
        tfish = twofish.Twofish(key)
        ciphertext = strxor(data, cls._gen_keystream(len(data), tfish, ctr))

        return iv + ciphertext
Exemplo n.º 7
0
    def decrypt(cls, data, key):
        if len(key) != cls.key_size:
            raise TripleSecFailedAssertion(u"Wrong Twofish key size")

        iv = data[:cls.block_size]
        ctr = Counter.new(cls.block_size*8, initial_value=int(binascii.hexlify(iv), 16))

        T = twofish.Twofish(key)
        return strxor(data[cls.block_size:], cls._gen_keystream(len(data[cls.block_size:]), T, ctr))
Exemplo n.º 8
0
def encrypt_login(binary_unenc, pack=DEFAULT_ZPACK):

    md = hashlib.md5()
    md.update(get_key())
    tf_key = md.digest()
    tf = twofish.Twofish(tf_key)

    enc_login = dtype_binary(tf.encrypt(binary_unenc.zpack(pack)))
    return enc_login
Exemplo n.º 9
0
    def decrypt(cls, data, key):
        validate_key_size(key, cls.key_size, "Twofish")

        ctr = BlockCipher.generate_decrypt_counter(data, cls.block_size)
        tfish = twofish.Twofish(key)

        return strxor(
            data[cls.block_size:],
            cls._gen_keystream(len(data[cls.block_size:]), tfish, ctr))
Exemplo n.º 10
0
    def encrypt(cls, data, key):
        if len(key) != cls.key_size:
            raise TripleSecFailedAssertion(u"Wrong Twofish key size")

        iv = rndfile.read(cls.block_size)
        ctr = Counter.new(cls.block_size*8, initial_value=int(binascii.hexlify(iv), 16))

        T = twofish.Twofish(key)
        ciphertext = strxor(data, cls._gen_keystream(len(data), T, ctr))
        return iv + ciphertext
Exemplo n.º 11
0
 def __init__(self, fp, key, iterations=None):
     self._fp = fp
     if iterations is None or iterations < self.MIN_HASH_ITERATIONS:
         iterations = self.MIN_HASH_ITERATIONS
     salt = os.urandom(32)
     K = os.urandom(32)
     L = os.urandom(32)
     p1 = self.stretch_key(key, salt, iterations)
     hp1 = hashlib.sha256(p1).digest()
     ff = twofish.Twofish(p1)
     b1 = ff.encrypt(K[:16])
     b2 = ff.encrypt(K[16:])
     b3 = ff.encrypt(L[:16])
     b4 = ff.encrypt(L[16:])
     self._fishfish = twofish.Twofish(K)
     self._hmac = hmac.new(L, digestmod=self.DIGESTMOD)
     self._iv = iv = os.urandom(16)
     header = Header(self.TAG, salt, iterations, hp1, b1, b2, b3, b4, iv)
     fp.write(header.to_bytes())
def run_test(dut, key=0):
    key = random.randint(0, (2**128) - 1)
    #print(hex(key))
    #key = 0
    twofish_SW = twofish.Twofish(key)
    expected_Me = twofish_SW.M_e
    expected_Mo = twofish_SW.M_o
    expected_Si = twofish_SW.S_i
    setup_function(dut, key)
    yield calculate_values(dut, expected_Me, expected_Mo, expected_Si)
def run_test(dut, key = 0):
    #key = random.randint(0,(2**128)-1)
    #print(hex(key))
    key = random.randint(0,(2**128)-1)
    R0 = random.randint(0,(2**32)-1)
    R1 = random.randint(0,(2**32)-1)
    R2 = random.randint(0,(2**32)-1)
    R3 = random.randint(0,(2**32)-1)
    twofish_SW = twofish.Twofish(key)
    Me = twofish_SW.M_e
    Mo = twofish_SW.M_o
    Si = twofish_SW.S_i

    expected_enc_values = []
    expected_dec_values = []

    for i in range (0,16):
       
        enc_values = twofish.enc_stage(R0,R1,R2,R3,Me,Mo,Si,i)
        expected_enc_values.append(enc_values[0])
        expected_enc_values.append(enc_values[1])
        expected_enc_values.append(enc_values[2])
        expected_enc_values.append(enc_values[3])
        dec_values = twofish.dec_stage(R0,R1,R2,R3,Me,Mo,Si,i)
        expected_dec_values.append(dec_values[0])
        expected_dec_values.append(dec_values[1])
        expected_dec_values.append(dec_values[2])
        expected_dec_values.append(dec_values[3])


    #encrypt
    print("ENCRYPT")
    enc_dec = 0
    
    

    setup_function(dut,Me,Mo,Si,R0,R1,R2,R3,enc_dec)
    yield calculate_values(dut,expected_enc_values)

    #decrypt
    print("DECRYPT")
    enc_dec = 1
    
    

    setup_function(dut,Me,Mo,Si,R0,R1,R2,R3,enc_dec)
    yield calculate_values(dut,expected_dec_values)
Exemplo n.º 14
0
def run_test(dut, key=0):
    #key = random.randint(0,(2**128)-1)
    #print(hex(key))
    key = random.randint(0, (2**128) - 1)
    twofish_SW = twofish.Twofish(key)
    Me = twofish_SW.M_e
    Mo = twofish_SW.M_o

    expected_values = []

    for i in range(0, 16):
        k_values = twofish.generate_K_values(i, Me, Mo)
        expected_values.append(k_values[0])
        expected_values.append(k_values[1])

    setup_function(dut, Me, Mo)
    yield calculate_values(dut, expected_values)
Exemplo n.º 15
0
def run_test(dut, key=0):
    #key = random.randint(0,(2**128)-1)
    #print(hex(key))
    key = random.randint(0, (2**128) - 1)
    R0 = random.randint(0, (2**32) - 1)
    R1 = random.randint(0, (2**32) - 1)
    twofish_SW = twofish.Twofish(key)
    Me = twofish_SW.M_e
    Mo = twofish_SW.M_o
    Si = twofish_SW.S_i

    expected_values = []

    for i in range(0, 16):
        f_values = twofish.function_F(R0, R1, i, Me, Mo, Si)
        expected_values.append(f_values[0])
        expected_values.append(f_values[1])

    setup_function(dut, Me, Mo, Si, R0, R1)
    yield calculate_values(dut, expected_values)
Exemplo n.º 16
0
def run_test(dut, key=0, text=0):
    key = random.randint(0, (2**128) - 1)
    text = random.randint(0, (2**128) - 1)

    #key = 0x0
    #text = 0x0
    twofish_SW = twofish.Twofish(key)

    #encrypt
    print("ENCRYPT")
    enc_dec = 0
    expected_value = twofish_SW.encrypt(text)

    setup_function(dut, key, enc_dec, text)
    yield rst_function_test(dut, enc_dec)
    yield enc_dec_test(dut, expected_value)
    #decrypt
    print("DECRYPT")
    enc_dec = 1
    expected_value = twofish_SW.decrypt(text)

    setup_function(dut, key, enc_dec, text)
    yield rst_function_test(dut, enc_dec)
    yield enc_dec_test(dut, expected_value)
Exemplo n.º 17
0
def load(f, password):
    l.debug('Reading header ...')
    tag = f.read(4)
    if tag != TAG:
        raise PSafe3FormatError("Tag is wrong.  Is this a PSafe3 file?")
    salt = f.read(32)
    niter = struct.unpack("<I", f.read(4))[0]

    l.debug('Stretching password ...')
    P2 = stretch_key(password, salt, niter)
    HP2 = hashlib.sha256(P2).digest()
    if HP2 != f.read(32):
        raise BadPasswordError

    l.debug('Reading header ...')
    m = twofish.Twofish(P2)
    K = m.decrypt(f.read(16)) + m.decrypt(f.read(16))
    L = m.decrypt(f.read(16)) + m.decrypt(f.read(16))
    IV = f.read(16)

    m = twofish.Twofish(K)
    prev_ct = IV

    l.debug('Decrypting ...')
    plaintext = ''
    hmac_data = ''
    while True:
        ct = f.read(16)
        if ct == EOF:
            break
        plaintext += sxor(m.decrypt(ct), prev_ct)
        prev_ct = ct

    l.debug('Reading decrypted header ...')
    g = StringIO.StringIO(plaintext)
    in_header = True
    header = {}
    record = {}
    records = []
    had = set()
    while True:
        field = g.read(5)
        if not field:
            break
        length, t = struct.unpack("<IB", field)
        d = g.read(length)
        hmac_data += d
        if t in had:
            l.warn("Field type %s occurs twice", t)
        had.add(t)
        if in_header:
            if t == 0:
                header['version'] = struct.unpack("<H", d)[0]
            elif t == 1:
                header['uuid'] = uuid.UUID(bytes=d)
            elif t == 2:
                header['non-default-preferences'] = d
            elif t == 3:
                header['tree-display-status'] = d
            elif t == 4:
                header['last-save'] = unpack_ts(d)
            elif t == 5:
                header['last-save-who'] = d
            elif t == 6:
                header['last-save-what'] = d
            elif t == 7:
                header['last-save-by-user'] = d
            elif t == 8:
                header['last-save-on-host'] = d
            elif t == 9:
                header['database-name'] = d
            elif t == 10:
                header['database-description'] = d
            elif t == 11:
                header['database-filters'] = d
            elif t == 15:
                header['recently-used-filters'] = d
            elif t == 16:
                header['named-password-policies'] = d
            elif t == 17:
                header['empty-groups'] = d
            elif t == 255:
                in_header = False
                had = set()
            else:
                l.warn("Unknown header field: type %s; data %s", t, repr(d))
        else:
            if t == 1:
                record['uuid'] = uuid.UUID(bytes=d)
            elif t == 2:
                record['group'] = d
            elif t == 3:
                record['title'] = d
            elif t == 4:
                record['username'] = d
            elif t == 5:
                record['notes'] = d
            elif t == 6:
                record['password'] = d
            elif t == 7:
                record['creation-time'] = unpack_ts(d)
            elif t == 8:
                record['password-modification-time'] = unpack_ts(d)
            elif t == 9:
                record['last-access-time'] = unpack_ts(d)
            elif t == 10:
                record['password-expiry-time'] = unpack_ts(d)
            elif t == 12:
                record['last-modification-time'] = unpack_ts(d)
            elif t == 13:
                record['url'] = d
            elif t == 14:
                record['autotype'] = d
            elif t == 15:
                record['password-history'] = d
            elif t == 16:
                record['password-policy'] = d
            elif t == 17:
                record['password-expiry-interval'] = d
            elif t == 18:
                record['run-command'] = d
            elif t == 19:
                record['double-click-action'] = d
            elif t == 20:
                record['email-address'] = d
            elif t == 21:
                record['protected-entry'] = (d != chr(0))
            elif t == 22:
                record['own-symbols-for-password'] = d
            elif t == 23:
                record['shift-double-click-action'] = d
            elif t == 24:
                record['password-policy-name'] = d
            elif t == 255:
                records.append(record)
                record = {}
                had = set()
            else:
                l.warn("Unknown record field: type %s; data %s", t, repr(d))
        tl = length + 5
        if tl % 16 != 0:
            g.read(16 - (tl % 16))
    l.debug('Checking HMAC ...')
    if hmac.new(L, hmac_data, hashlib.sha256).digest() != f.read(32):
        raise IntegrityError
    return (header, records)
Exemplo n.º 18
0
 def _create_impl(cls, key):
     return twofish_impl.Twofish(bytes(key))
Exemplo n.º 19
0
 def __init__(self, key):
     """
     Set the key to be used for en-/de-cryption.
     """
     self.twofish = twofish.Twofish()
     self.twofish.set_key(key)
Exemplo n.º 20
0
 def __init__(self, key, *args, **kwargs):
     self.tf = twofish.Twofish(key)
     _BlockCipher.__init__(self, *args, **kwargs)