예제 #1
0
def register(logi=None, passw=None):
    if logi is None and passw is None:
        login = input("Please input login:"******"Please input password:"******"localhost"
    make_user = True
    session = Session()
    while make_user:
        port = random.randint(10000, 60000)
        try:
            print(session.query(Nodes).filter(Nodes.port == port).one())
        except NoResultFound:
            u = Nodes(login=login_hash.hexdigest(),
                      password=password_hash.hexdigest(),
                      ip_address=ip_address,
                      port=port,
                      is_available=False,
                      rating=0)
            session.add(u)
            session.commit()
            make_user = False
        else:
            print("User in base")
    session.close()
    return True
예제 #2
0
def connect(logi=None, passwd=None, serv=False):
    if serv:
        login = "******".encode()
        password = "******".encode()
    else:
        login = logi.encode()
        password = passwd.encode()
    login_hash = SHA3_512.new(login)
    password_hash = SHA3_512.new(password)
    session_connect = Session()
    try:
        conn_node = session_connect.query(Nodes).filter(
            and_(Nodes.login == login_hash.hexdigest(),
                 Nodes.password == password_hash.hexdigest()))
    except NoResultFound:
        if not serv:
            print("Wrong login")
        else:
            server = Nodes(login=login_hash.hexdigest(),
                           password=password_hash.hexdigest(),
                           ip_address="localhost",
                           port=49001,
                           is_available=False)
            session_connect.add(server)
            session_connect.commit()
        session_connect.close()
        return None
    else:
        keys = [
            str(random.randint(1, 10000000)),
            str(random.randint(10000001, 100000001))
        ]
        # keys = create_rsa()
        # print("Here is your private key, save it\n", keys[1])
        # print("Here is your public key, save it\n", keys[0])
        conn_node.update({Nodes.is_available: True, Nodes.id: keys[0]})
        session_connect.commit()
        session_connect.close()
        if serv:
            node = Node(conn_node.one().ip_address,
                        conn_node.one().port,
                        keys[0],
                        server_s=True)
        else:
            node = Node(conn_node.one().ip_address,
                        conn_node.one().port, keys[0])
        node.start()
        return node
예제 #3
0
 def switch_dict(size):
     return {
         224: SHA3_224.new(objectToHash.encode('utf-8')),
         256: SHA3_256.new(objectToHash.encode('utf-8')),
         384: SHA3_384.new(objectToHash.encode('utf-8')),
         512: SHA3_512.new(objectToHash.encode('utf-8'))
     }.get(size, None)
예제 #4
0
def encrypt(inpath, outpath, password):
    filename = os.path.basename(inpath)
    salt = secrets.token_bytes(32)
    print("Deriving key.")
    key = scrypt(password=password, salt=salt, key_len=32, N=N, r=r, p=p)

    print("Reading file.")
    with open(inpath, 'rb') as inf:
        in_data = pad(inf.read(), 16)

    print("Encrypting.")
    e = AES.new(key, AES.MODE_ECB)
    out_data = e.encrypt(in_data)
    #EtM
    h = SHA3_512.new(key + out_data).digest()

    padded_filename = pad(filename.encode('utf-8')[:255], 256)
    e_filename = e.encrypt(padded_filename)

    print("Writing file.")
    with open(outpath, 'wb') as outf:
        outf.write(salt)
        outf.write(h)
        outf.write(e_filename)
        outf.write(out_data)
    def test_update_after_digest(self):
        msg = b("rrrrttt")

        # Normally, update() cannot be done after digest()
        h = SHA3.new(data=msg[:4])
        dig1 = h.digest()
        self.assertRaises(TypeError, h.update, msg[4:])
        dig2 = SHA3.new(data=msg).digest()

        # With the proper flag, it is allowed
        h = SHA3.new(data=msg[:4], update_after_digest=True)
        self.assertEquals(h.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h.update(msg[4:])
        self.assertEquals(h.digest(), dig2)
예제 #6
0
    def test_update_after_digest(self):
        msg=b("rrrrttt")

        # Normally, update() cannot be done after digest()
        h = SHA3.new(data=msg[:4])
        dig1 = h.digest()
        self.assertRaises(TypeError, h.update, msg[4:])
        dig2 = SHA3.new(data=msg).digest()

        # With the proper flag, it is allowed
        h = SHA3.new(data=msg[:4], update_after_digest=True)
        self.assertEquals(h.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h.update(msg[4:])
        self.assertEquals(h.digest(), dig2)
예제 #7
0
 def verify_with_hash(self, passwd):
     #hash(hash(pw+pw_salt)+ver_salt)=hash(pw_hash+ver_salt)
     h = SHA3_512.new()
     h.update(passwd + self.__salt)
     if h.digest() != self.__pwhash:
         raise UnverifiedAccountError(
             "The account needs to be verified to get the file")
예제 #8
0
def checkPwd(passwd, salt, input_file_path):
    input_file = open(input_file_path, 'rb')
    bytes_temp = input_file.read(112)
    hashed_pwd = bytes_temp[48:112]

    return SHA3_512.new(
        data=passwd.encode('utf-8')).update(salt).digest() == hashed_pwd
예제 #9
0
    def encapsulate(self):
        m = secrets.randbits(256).to_bytes(32, 'big')
        G = SHA3_512.new()
        G.update(m)
        theta = G.digest()

        u, v = self.encrypt(m, theta)
        K_generator = SHA3_512.new()
        K_generator.update(m + u + v)
        K = K_generator.digest()

        d_generator = SHA512.new()
        d_generator.update(m)
        d = d_generator.digest()

        return K, u, v, d
 def H2(self, G2):
     s = str(G2)
     h = SHA3_512.new()
     h.update(s.encode('utf-8'))
     s_hash = h.digest()
     H2_hash = s_hash[:math.ceil(self.key.logp / 8)]
     return H2_hash
예제 #11
0
 def sign(self, message, privKeyPath, password):
     if type(message) is str:
         message = message.encode('utf-8')
     key = RSA.importKey(BasicFunctions.binaryReader(privKeyPath), password)
     Hash = SHA3_512.new(message)
     signature = pss.new(key).sign(Hash)
     return signature
def decrypt():
    # destinazione file password criptate
    path = input('File password criptate: ')
    fe = open(path, 'r')
    # destinazione file password in chiaro
    path = input('File password decriptate: ')
    fd = open(path, 'w')
    # leggi l'hash della chiave di criptazione
    hashed_key = binascii.a2b_base64(fe.readline().encode())
    # richiedi chiave e verifica che i digest corrispondano
    hk = ''
    while hk != hashed_key:
        key = pad(input('Key: ').encode(), 16)
        hk = SHA3_512.new(key).digest()
        if hk != hashed_key:
            print('Wrong key!')
    # decripta le password e scrivile insieme al resto nel file di uscita
    aes = AES.new(key, AES.MODE_ECB)
    for i in fe:
        l = i.split()
        for j in range(len(l) - 1):
            fd.write(l[j] + ' ')
        fd.write(
            unpad(aes.decrypt(binascii.a2b_base64(l[-1].encode())),
                  16).decode() + '\n')
    fe.close()
    fd.close()
예제 #13
0
    def __init__(self, signatureFile, hashAlgorithm, keyLength, privateKeyE):

        self.signatureFile = open(signatureFile, "w")
        self.hashAlgorithmName = hashAlgorithm
        self.keyLength = keyLength
        self.privateKey = privateKeyE  #tuple of (n, e, d)

        if hashAlgorithm == 'SHA-2-224':
            self.hashAlgorithm = SHA224.new()

        elif hashAlgorithm == 'SHA-2-256':
            self.hashAlgorithm = SHA256.new()

        elif hashAlgorithm == 'SHA-2-384':
            self.hashAlgorithm = SHA384.new()

        elif hashAlgorithm == 'SHA-2-512':
            self.hashAlgorithm = SHA512.new()

        elif hashAlgorithm == 'SHA-3-224':
            self.hashAlgorithm = SHA3_224.new()

        elif hashAlgorithm == 'SHA-3-256':
            self.hashAlgorithm = SHA3_256.new()

        elif hashAlgorithm == 'SHA-2-384':
            self.hashAlgorithm = SHA3_384.new()

        elif hashAlgorithm == 'SHA-2-256':
            self.hashAlgorithm = SHA3_512.new()

        else:
            raise Exception("Invalid hash function: " + hashAlgorithm)
예제 #14
0
    def hash_with_sha3_512(self, plaintext):

        hash = SHA3_512.new()
        if self.salt != "":
            plaintext = self.salt + plaintext
        hash.update(plaintext.encode("utf-8"))
        return hash.hexdigest()
예제 #15
0
def get_sha3_512(data: str) -> dict:
    """
    Returns the SHA3_512 hash value (hex).
    """
    sha3_512_call = SHA3_512.new()
    sha3_512_call.update(data.encode('utf-8'))
    return {"SHA3_512_hex": sha3_512_call.hexdigest()}
예제 #16
0
    def __init__(self, amount, recepient_pk):
        super().__init__(recepient_pk)

        self.coins = []
        for i in range(amount):
            self.coins.append(str(self.id) + '/' + str(i))
        self.hash = SHA3_512.new(
            str.encode(str(self.coins) + str(self.recepient_pk)))
예제 #17
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("string_to_sha", help="The string to do sha for")
    args = parser.parse_args()

    h = SHA3_512.new()
    h.update(args.string_to_sha)
    print(h.hexdigest())
예제 #18
0
def testSignature(signatureFile, originalFile, pubFile):

    pubKeyL, n, e = readPublicKey(pubFile)

    public_key = RSA.construct((n, e))

    verifier = PKCS1_v1_5.new(public_key)

    fileName, hashed, key, signature = readSignature(signatureFile)

    (hashing, hashingKeyL) = hashed

    (enc, encKeyL) = key

    assert fileName == originalFile

    assert enc == 'RSA'

    assert encKeyL == pubKeyL

    hashAlgorithm = hashing + "-" + str(hashingKeyL)

    if hashAlgorithm == 'SHA-2-224':
        hashAlgorithm = SHA224.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA384.new()

    elif hashAlgorithm == 'SHA-2-512':
        hashAlgorithm = SHA512.new()

    elif hashAlgorithm == 'SHA-3-224':
        hashAlgorithm = SHA3_224.new()

    elif hashAlgorithm == 'SHA-3-256':
        hashAlgorithm = SHA3_256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA3_384.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA3_512.new()

    else:
        raise Exception("Invalid hash function: " + hashAlgorithm)

    data = open(originalFile, "rb").read()

    hashAlgorithm.update(data)

    assert verifier.verify(hashAlgorithm, signature)

    print("SIGNATURE TEST SUCCESSFUL!!")
예제 #19
0
 def __init__(self, sender_pk, sender_signature, recepient_pk, coins):
     super().__init__(recepient_pk)
     self.sender_pk = sender_pk
     self.sender_signature = sender_signature
     self.recepient_pk = recepient_pk
     self.coins = coins
     self.hash = SHA3_512.new(
         str.encode(
             str(sender_pk) + str(sender_signature) + str(recepient_pk) +
             str(coins)))
예제 #20
0
def get_hash(msg, hash_size):
    if hash_size == "224":
        hash = SHA3_224.new(msg)
    if hash_size == "256":
        hash = SHA3_256.new(msg)
    if hash_size == "384":
        hash = SHA3_384.new(msg)
    if hash_size == "512":
        hash = SHA3_512.new(msg)
    return hash
예제 #21
0
def testSeal_verification(signatureFile, envelopeFile, pubFile):

    pubKeyL, n, e = readPublicKey(pubFile)

    public_key = RSA.construct((n, e))

    verifier = PKCS1_v1_5.new(public_key)

    fileName, hashed, key, signature = readSignature(signatureFile)

    (hashing, hashingKeyL) = hashed

    (enc, encKeyL) = key

    assert enc == 'RSA'

    assert encKeyL == pubKeyL

    hashAlgorithm = hashing + "-" + str(hashingKeyL)

    if hashAlgorithm == 'SHA-2-224':
        hashAlgorithm = SHA224.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA384.new()

    elif hashAlgorithm == 'SHA-2-512':
        hashAlgorithm = SHA512.new()

    elif hashAlgorithm == 'SHA-3-224':
        hashAlgorithm = SHA3_224.new()

    elif hashAlgorithm == 'SHA-3-256':
        hashAlgorithm = SHA3_256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA3_384.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA3_512.new()

    else:
        raise Exception("Invalid hash function: " + hashAlgorithm)

    fileName, simConf, rsaConf, data, cryptKey, mode, iv = readEnvelope(
        envelopeFile)

    hashAlgorithm.update(data + cryptKey)

    assert verifier.verify(hashAlgorithm, signature)

    print("SEAL SIGNATURE TEST SUCCESSFUL!!")
예제 #22
0
def salted_hash(password: str,
                salt: bytes = None,
                num_iter: int = 10000) -> Tuple[bytes, bytes]:
    """
    Generates the salted hash of a plaintext `password`. If parameter `salt` is not set, a random salt will be used.
    `num_iter` is the number of iterations to apply the hash algorithm.

    The hash algorithm used here is the SHA3-512, so the resulted hash is 64 bytes long and the salt is of the same
    size.

    :return: Salted hash of the `password` and the salt used.
    """
    if not salt:
        salt = Random.get_random_bytes(64)
    password_hash = password.encode()
    for i in range(num_iter):
        password_hash = SHA3_512.new(data=password_hash).digest()
        if i > num_iter // 2:
            password_hash = password_hash + salt
    return SHA3_512.new(data=password_hash).digest(), salt
예제 #23
0
 def verify(self, message, pubKeyPath, signature):
     if type(message) is str:
         message = message.encode('utf-8')
     key = RSA.importKey(BasicFunctions.binaryReader(pubKeyPath))
     Hash = SHA3_512.new(message)
     verifier = pss.new(key)
     try:
         verifier.verify(Hash, signature)
     except (ValueError, TypeError):
         return False
     return True
예제 #24
0
    def hash(self, message):
        message = bytes(message.encode())
        h_obj = SHA3_512.new()
        start_time = timer()
        h_obj.update(message)
        self.executionTime = timer() - start_time
        return h_obj.hexdigest().upper()


# message = b""
# sha_3 = SHA_3()
# print( sha_3.hash(message) )
예제 #25
0
    def decapsulate(self, u, v, d):
        mbar = self.decrypt(u, v)

        G = SHA3_512.new()
        G.update(mbar)
        thetabar = G.digest()

        ubar, vbar = self.encrypt(mbar, thetabar)

        assert ubar == u and vbar == v

        d_generator = SHA512.new()
        d_generator.update(mbar)
        dbar = d_generator.digest()

        assert dbar == d

        K_generator = SHA3_512.new()
        K_generator.update(mbar + u + v)
        K = K_generator.digest()

        return K
예제 #26
0
def main():
    with open(r'C:\Temp\testData\sha3.dat', 'wb') as file:
        for i in range(1, 1000 + 1):
            with BytesIO() as ms:
                data = get_random_bytes(i)
                write_lv(ms, data)
                sha3 = SHA3_512.new(data)
                write_lv(ms, sha3.digest())

                ms.seek(0)
                record = ms.read()

            write_lv(file, record)
        write_lv(file, b'')
예제 #27
0
def hash(input_stream: BinaryIO) -> bytes:
    """Compute the SHA3_512 hash value

    :param input_stream: Input stream
    :return: SHA3_512 hash
    """
    hasher = SHA3_512.new()

    while True:
        buffer = input_stream.read(4096)
        if not buffer:
            break
        hasher.update(buffer)
    return hasher.digest()
예제 #28
0
def Hash_Function():
    if SelectedHashFunction.get() == "SHA-256":
        Hash = SHA256.new()
    elif SelectedHashFunction.get() == "SHA-512":
        Hash = SHA512.new()
    elif SelectedHashFunction.get() == "SHA3-256":
        Hash = SHA3_256.new()
    elif SelectedHashFunction.get() == "SHA3-512":
        Hash = SHA3_512.new()

    Password_String = PasswordEntry.get()
    Hash.update(Password_String.encode())
    Password_Digest = str(Hash.hexdigest())
    PasswordEntry.delete(0, "end")
    PasswordEntry.insert(0, Password_Digest)
예제 #29
0
def request_alias(author: Union[AccountId, str],
                  account: Union[AccountId, str], server: Server) -> str:
    """Generates an alias code for linking accounts together"""
    if server.has_account(account):
        raise AccountCommandException(account)
    author = _get_account(author, server)

    key = ECC.generate(curve='P-256')
    signer = DSS.new(key, 'fips-186-3')
    signature = base64.b64encode(
        signer.sign(SHA3_512.new(
            str(account).encode('utf-8')))).decode('utf-8')
    server.add_public_key(author, key.public_key())

    return signature
예제 #30
0
def hash(message):
    """
    Computes hash of message using SHA3-512

    parameters:
    message (bytes): message to be hashed

    return value:
    the computed hash as a string
    """
    # create a SHA3_512 object for hashing
    h_obj = SHA3_512.new()
    # compute hash of message
    h_obj.update(message)
    # return computed hash as a string
    return h_obj.hexdigest()
def encrypt():
    # raccogli i dati dal foglio Excel
    # analizza la prima riga
    done = False
    while not done:
        d = input("File xlsx: ")
        workbook = xlrd.open_workbook(d)
        worksheet = workbook.sheet_by_index(0)
        first_row = []
        for col in range(worksheet.ncols):
            first_row.append(worksheet.cell_value(0, col))
        if 'Sito' not in first_row or 'Username' not in first_row or 'Password' not in first_row:
            print(
                'Nella prima riga devono essere presenti "Sito", "Username" e "Password"'
            )
        else:
            done = True
    # crea un dizionario per ogni riga di dati
    data = []
    for row in range(1, worksheet.nrows):
        elm = {}
        for col in range(1, worksheet.ncols):
            elm[first_row[col]] = worksheet.cell_value(row, col)
        data.append(elm)
    data.sort(key=lambda x: x['Sito'])
    # richiedi una chiave
    key = ''
    while not key or len(key) > 16:
        key = input('Key (max 16 bytes): ')
    if len(key) < 16:
        key = pad(key.encode(), 16)
    else:
        key = key.encode()
    aes = AES.new(key, AES.MODE_ECB)
    # destinazione file password criptate
    path = input('File password criptate: ')
    f = open(path, 'w')
    # scrivi hash della chiave
    f.write(binascii.b2a_base64(SHA3_512.new(key).digest()).decode())
    # per ogni riga di dati che contiene una password scrivi il sito, lo username e la password criptata in base64
    for i in data:
        if i['Password']:
            f.write(i['Sito'] + ' ' + i['Username'] + ' ')
            padded_password = pad(i['Password'].encode(), 16)
            f.write(binascii.b2a_base64(aes.encrypt(padded_password)).decode())
    f.close()