Exemplo n.º 1
0
def compute_rw(k_s):
    """
    Cette méthode va calculer rw en fonction du password
    :return: rw en format digest
    """
    # On hash le password
    blk2 = BLAKE2b.new(digest_bits=256)
    blk2.update(PWD.encode())
    # On calcule H' (ks * H(pwd) * g)
    H_prime = (k_s * Integer("0x" + blk2.hexdigest())).lift() * g

    # On fait en sorte que x et y de H' soient de la même taille en les paddant
    x, y = pad(H_prime)

    bytearray_x = bytearray(bitstring_to_bytes(x))
    bytearray_y = bytearray(bitstring_to_bytes(y))

    # On passe le password en byrearray pour le concatener avec x et y de H'
    bytearray_password = bytearray(PWD.encode())

    data = bytearray_password + bytearray_x + bytearray_y

    blk2 = BLAKE2b.new(digest_bits=256)
    blk2.update(data)
    rw = blk2.digest()
    return rw
def hashPsw(psw: bytes, salt: bytes) -> bytes:
    saltedPsw = salt + psw
    if hashingAlgorith == sha3:
        return hash.new(saltedPsw).digest()
    if hashingAlgorith == blake2:
        h = hash.new(digest_bits=512)
        return h.update(saltedPsw).digest()
Exemplo n.º 3
0
def compute_ssid_prime(sid, ssid, alpha):
    """
    Cette méthode va calculer ssid'
    :param sid: l'id de l'utilisateur courant
    :param ssid: l'id de session courante
    :param alpha: alpha reçu du client
    :return: ssid'
    """
    # on va passer le ssid en binaire et on va padder jusqu'a 128, cela laisse des pareametre de 16 characters
    ssid_bin = ''.join('{0:08b}'.format(ord(x), 'b') for x in ssid)
    if len(ssid_bin) < 128:
        diff = 128 - len(ssid_bin)
        ssid_bin = '0' * diff + ssid_bin

    # On fait en sorte que x et y soit sur 256 bit
    x, y = pad(alpha)

    bytearray_x = bytearray(bitstring_to_bytes(x))
    bytearray_y = bytearray(bitstring_to_bytes(y))
    bytearray_ssid = bytearray(bitstring_to_bytes(ssid_bin))
    bytearray_sid = bytearray(sid.to_bytes(16, byteorder='big'))

    blk2 = BLAKE2b.new(digest_bits=256)
    blk2.update(bytearray_sid + bytearray_ssid + bytearray_x + bytearray_y)

    return blk2.digest()
Exemplo n.º 4
0
def compute_K(X_s, P_s, e_s, x_u, e_u, p_u):
    """
    Calcule de K (HMQV)
    :param X_s: X_s du server
    :param P_s: Clé public du server
    :param e_u: e_u de la session
    :param x_u: x_s du client
    :param e_s: e_s de la session
    :param p_u: Clé privé du client
    :return: la clé K
    """

    # On vérifie que nos point soient bien sur notre courbe
    if not is_point_on_G(X_s) or not is_point_on_G(P_s):
        raise TypeError

    KE = ((P_s * e_s.lift()) + X_s) * (x_u + (e_u * p_u)).lift()
    # On fait en sorte que x et y soient sur 256 bits
    x, y = pad(KE)
    bytearray_x = bytearray(bitstring_to_bytes(x))
    bytearray_y = bytearray(bitstring_to_bytes(y))

    blk2 = BLAKE2b.new(digest_bits=256)
    blk2.update(bytearray_x + bytearray_y)
    return blk2.digest()
Exemplo n.º 5
0
        def testSignVerify(self):
            rng = Random.new().read
            key = RSA.generate(1024, rng)

            for hashmod in (MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, RIPEMD160):
                hobj = hashmod.new()
                hobj.update(b('blah blah blah'))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2b has variable digest size
            for digest_bits in (160, 256, 384, 512):
                hobj = BLAKE2b.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2b supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2s too
            for digest_bits in (128, 160, 224, 256):
                hobj = BLAKE2s.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2s supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)
Exemplo n.º 6
0
    def blake_2b(self, bits: int = 256, key: bytes = ""):
        """Get Balke-2b hash
        
        Performs BLAKE2b hashing on the input. BLAKE2b is a flavour of the 
        BLAKE cryptographic hash function that is optimized for 64-bit 
        platforms and produces digests of any size between 1 and 64 bytes. 
        Supports the use of an optional key.
        
        Args:
            bits (int, optional): Number of digest bits, by default 256
            key (bytes, optional): Encryption secret key, by default ''
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("A").blake_2b(bits=128, key="key").output
            "6d2e4cba3bc564e02d1a76f585a6795d"
        """
        assert bits in [
            512,
            384,
            256,
            160,
            128,
        ], "Valid bits are 512, 384, 256, 160, 128"
        h = BLAKE2b.new(digest_bits=bits, key=key.encode())
        h.update(self._convert_to_bytes())
        self.state = h.hexdigest()
        return self
Exemplo n.º 7
0
    def testSignVerify(self):
        rng = Random.new().read
        key = RSA.generate(1024, rng)

        for hashmod in (MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512,
                        RIPEMD160):
            hobj = hashmod.new()
            hobj.update(b('blah blah blah'))

            signer = PKCS.new(key)
            signature = signer.sign(hobj)
            signer.verify(hobj, signature)

        # Blake2b has variable digest size
        for digest_bits in (160, 256, 384, 512):
            hobj = BLAKE2b.new(digest_bits=digest_bits)
            hobj.update(b("BLAKE2b supports several digest sizes"))

            signer = PKCS.new(key)
            signature = signer.sign(hobj)
            signer.verify(hobj, signature)

        # Blake2s too
        for digest_bits in (128, 160, 224, 256):
            hobj = BLAKE2s.new(digest_bits=digest_bits)
            hobj.update(b("BLAKE2s supports several digest sizes"))

            signer = PKCS.new(key)
            signature = signer.sign(hobj)
            signer.verify(hobj, signature)
Exemplo n.º 8
0
async def change(data, **kwargs):
    signature = data["signature"]
    address = data["address"]
    blockID = data["id"]

    valid = await verifySignature(signature, address, data)
    if not valid:
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "signature"
        }
        return toRespond

    preID = data.copy()
    preID.pop("signature")
    preID.pop("id")

    hasher = BLAKE2b.new(digest_bits=512)
    realID = hasher.update(json.dumps(preID).encode("utf-8")).hexdigest()
    if blockID != realID:
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "id"
        }
        return toRespond

    previousBlock = await getBlock(address, data["previous"])
    # Check that balance has not changed
    if float(data["balance"]) != float(previousBlock["balance"]):
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "balance"
        }
        return toRespond

    if data["representative"] not in os.listdir(
            ledgerDir):  # If account to be delegated to does not exist
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "link"
        }
        return toRespond

    toRespond = {
        "type": "confirm",
        "action": "delegate",
        "address": address,
        "id": blockID
    }
    return toRespond
Exemplo n.º 9
0
def compute_alpha(password):
    """
    Cette méthode va calculer alpha
    :param password: le password utilisé pour pacluler alpha
    :return: alpha
    """
    blk2 = BLAKE2b.new(digest_bits=256)

    blk2.update(password.encode())
    return (r * Integer("0x" + blk2.hexdigest())).lift() * g
Exemplo n.º 10
0
async def receive(sendAmount, block):
    global websocket

    resp = await wsRequest(
        f'{{"type": "balance", "address": "{publicKeyStr}"}}')
    resp = json.loads(resp)

    if resp["type"] != "rejection":
        balance = float(resp["balance"])
        blockType = "receive"
        response = await wsRequest(
            f'{{"type": "getPrevious", "address": "{publicKeyStr}"}}')
        previous = json.loads(response)["link"]

    else:
        balance = 0
        blockType = "open"
        previous = "0" * 20

    response = await wsRequest(
        json.dumps({
            "type": "getRepresentative",
            "address": publicKeyStr
        }))
    representative = json.loads(response)["representative"]

    block = {
        "type": f"{blockType}",
        "previous": f"{previous}",
        "address": f"{publicKeyStr}",
        "link": f"{block}",
        "balance": balance + float(sendAmount),
        "representative": representative
    }

    hasher = BLAKE2b.new(digest_bits=512)
    blockID = hasher.update(json.dumps(block).encode("utf-8")).hexdigest()
    block["id"] = blockID
    signature = await genSignature(block, privateKey)
    block = {**block, **{"signature": signature}}
    resp = await wsRequest(json.dumps(block))
    resp = json.loads(resp)

    if resp["type"] == "confirm":
        receiveAmount = sendAmount
        newBalance = block["balance"]
        print(f"\nReceived MXC: {receiveAmount}")
        print(f"New Balance: {newBalance}")
        print("Send or Delegate? (s/d)")

    else:
        print("\nFailed to receive MXC!")
        print(resp)
Exemplo n.º 11
0
def addDealWithSign (idSender, idReceiver, amount, signature):

	key = str(idSender) + '|' + str(idReceiver)  + '|' + str(amount)

	signature = binascii.unhexlify(signature.encode())

	connexion = sqlite3.connect("DataBase/tchai.db")
	cur = connexion.cursor()
	#1er methode avec seulement le montant
	sql = 'SELECT public_key FROM person where id_person=?;'
	cur.execute(sql,[idSender])

	for row in cur:
		pub = row[0]

	public = RSA.importKey(pub)
	
	# Verify valid PKCS#1 v1.5 signature (RSAVP1)
	hash = BLAKE2b.new()
	hash.update(key.encode())
	verifier = PKCS115_SigScheme(public)

	try:
		verifier.verify(hash, signature)
		#print("Signature is valid.")
		#1er methode avec seulement le montant
		sql = 'SELECT id_transaction, hash FROM deal;'
		cur.execute(sql)

		for row in cur:
			oldHash = row[1]
			lastId = row[0]

		amountFloat = float(amount)
		key = str(idSender) + '|' + str(idReceiver)  + '|' + str(amountFloat)	
		key = key + '|' + oldHash 
		#hash
		ahash = blake2b(key.encode()).hexdigest()
		sql = "INSERT INTO deal (amount, sender, receiver, hash) VALUES (?,?,?,?)"
		cur.execute(sql,[amount, idSender, idReceiver, ahash])
		connexion.commit()
		cur.close()
		connexion.close()
		return 'Deal Done.\n', 200

	except:
		#print("Signature is invalid.")
		return 'Vous n\'êtes pas '+ idSender +' .\n', 403
Exemplo n.º 12
0
async def decrypt_from_keystore(keystore: Keystore, password: str):
    """ Get the phrase from the keystore

    Args:
        keystore (Keystore): keystore
        password (str): password

    Raises:
        Exception: if password is incorrect
        Exception: any inner exceptions

    Returns:
        [type]: the phrase from keystore
    """
    if not isinstance(keystore, Keystore):
        keystore = Keystore.from_dict(keystore)

    kdfparams = keystore.crypto.kdfparams
    try:
        derived_key = await utils.pbkdf2(
            password,
            bytes.fromhex(kdfparams.salt),
            kdfparams.c,
            kdfparams.dklen,
            HASHFUNCTION,
        )

        cipherbytes = bytes.fromhex(keystore.crypto.ciphertext)

        blake256 = BLAKE2b.new(digest_bits=256)
        blake256.update((derived_key[16:32] + cipherbytes))
        mac = blake256.hexdigest()

        if mac != keystore.crypto.mac:
            raise Exception("Invalid Password")

        ctr = Counter.new(NBITS,
                          initial_value=int(keystore.crypto.cipherparams.iv,
                                            16))
        aes_decipher = AES.new(derived_key[0:16], AES.MODE_CTR, counter=ctr)

        decipher_bytes = aes_decipher.decrypt(cipherbytes)

        res = bytes.decode(decipher_bytes)
        return res

    except Exception as err:
        raise Exception(err)
Exemplo n.º 13
0
def create_fingerprint(key):
    """
    Generates and returns a fingerprint for a given key.

    Args:
        key: The Crypto.PublicKey.RSA.RsaKey to fingerprint.

    Returns:
        The fingerprint of the key.
    """
    hasher = BLAKE2b.new(digest_bits=256)
    hasher.update(key.export_key())
    hash_bytes = hasher.digest()
    b32 = b32encode(hash_bytes)
    fingerprint = "-".join(b32[n:n+4].decode() for n in range(0, len(b32), 4))
    return fingerprint[:-5]
Exemplo n.º 14
0
def compute_rw(_beta, p):
    """
    Cette methode va calculer rw
    :param _beta: beta recu de la part du serveur
    :param p: le password de l'utilisateur
    :return: rw en digest mode
    """
    beta_calc = _beta * (1 / r).lift()

    x, y = pad(beta_calc)
    bytearray_x = bytearray(bitstring_to_bytes(x))
    bytearray_y = bytearray(bitstring_to_bytes(y))

    bytearray_password = bytearray(p.encode())

    blk2 = BLAKE2b.new(digest_bits=256)
    blk2.update(bytearray_password + bytearray_x + bytearray_y)
    return blk2.digest()
    def runTest(self):

        key = RSA.generate(1280)
        signer = pss.new(key)
        hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1", "SHA224",
                      "SHA256", "SHA384", "SHA512", "SHA3_224", "SHA3_256",
                      "SHA3_384", "SHA3_512")

        for name in hash_names:
            hashed = load_hash_by_name(name).new(b("Test"))
            signer.sign(hashed)

        from Crypto.Hash import BLAKE2b, BLAKE2s
        for hash_size in (20, 32, 48, 64):
            hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_b)
        for hash_size in (16, 20, 28, 32):
            hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_s)
Exemplo n.º 16
0
    def runTest(self):

        key = RSA.generate(1024)
        signer = pkcs1_15.new(key)
        hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1",
                      "SHA224", "SHA256", "SHA384", "SHA512",
                      "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512")

        for name in hash_names:
            hashed = load_hash_by_name(name).new(b("Test"))
            signer.sign(hashed)

        from Crypto.Hash import BLAKE2b, BLAKE2s
        for hash_size in (20, 32, 48, 64):
            hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_b)
        for hash_size in (16, 20, 28, 32):
            hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_s)
Exemplo n.º 17
0
def compute_e_u_or_e_s(point, prim):
    """
    Cette méthode va calculer e_u ou e_s
    :param point: le point qui va service pour le calcul
    :param prim: ssid'
    :return: e_u ou e_s
    """

    # On fait en sorte que x et y soient sur 256 bit
    x, y = pad(point)

    # On transforme tout en bytearray
    bytearray_ssid_prime = bytearray(prim)
    bytearray_x = bytearray(bitstring_to_bytes(x))
    bytearray_y = bytearray(bitstring_to_bytes(y))

    blk2 = BLAKE2b.new(digest_bits=256)
    blk2.update(bytearray_x + bytearray_y + bytearray_ssid_prime)
    # On creer un Integer depuis notre hexa puis on fait modulo q
    return Fq(Integer('0x' + blk2.hexdigest()))
Exemplo n.º 18
0
async def encrypt_to_keystore(phrase: str, password: str):
    """Get the Keystore from the given phrase and password.

    Args:
        phrase (str): phrase
        password (str): password

    Raises:
        Exception: if phrase is invalid

    Returns:
        [type]: Keystore
    """
    if not validate_phrase(phrase):
        raise Exception("Invalid BIP39 Phrase")

    ID = str(uuid.uuid4())
    salt = get_random_bytes(32)
    iv = get_random_bytes(16)

    kdfparams = KdfParams(prf=PRF , dklen=DKLEN , salt=salt.hex(),c=C)

    ciptherparams = CipherParams(iv.hex())


    derived_key = await utils.pbkdf2(
        password, salt, kdfparams.c, kdfparams.dklen, HASHFUNCTION
    )

    ctr = Counter.new(NBITS, initial_value=int(iv.hex(), 16))
    aes_cipher = AES.new(derived_key[0:16], AES.MODE_CTR, counter=ctr)
    cipherbytes = aes_cipher.encrypt(phrase.encode("utf8"))

    blake256 = BLAKE2b.new(digest_bits=256)
    blake256.update((derived_key[16:32] + cipherbytes))
    mac = blake256.hexdigest()

    crypto_struct = CryptoStruct("aes-128-ctr" , cipherbytes.hex() , ciptherparams ,KDF,kdfparams,mac)

    keystore = Keystore(crypto_struct , ID, 1 , META)
    return keystore
Exemplo n.º 19
0
def compute_K(X_u, P_u, e_u, x_s, e_s, p_s):
    """
    Calcule de K (HMQV)
    :param X_u: X_u du client
    :param P_u: Clé public du client
    :param e_u: e_u de la session
    :param x_s: x_s du serveur
    :param e_s: e_s de la session
    :param p_s: Clé privé du serveur
    :return: la clé K
    """
    if not is_point_on_G(X_u) or not is_point_on_G(P_u):
        raise TypeError

    KE = ((P_u * e_u.lift()) + X_u) * (x_s + (e_s * p_s)).lift()
    # On fait en sorte que x et y soient de la même longueur (256 bits)
    x, y = pad(KE)
    bytearray_x = bytearray(bitstring_to_bytes(x))
    bytearray_y = bytearray(bitstring_to_bytes(y))

    blk2 = BLAKE2b.new(digest_bits=256)
    blk2.update(bytearray_x + bytearray_y)
    return blk2.digest()
Exemplo n.º 20
0
    "d875c5b68e4c8c8d89fc7eac25d97b7428879f49f"
    "6ac0b3ef72a318b2fd62ff0b6ae690b4b7bb4cd2c"
    "34a0941c15f12cc84bcc95a41e0911b3d6580d3ec"
    "5f17634a96d821258d0d592e72d53bc35118ef152"
    "94d22c41fb8511077c7f1001b190d25ae3722c1ab"
    "2f34e6708ad8400b5a277e2b088872b981ae0c352"
    "e9377815755c7e78051704c38e49f62571a64b716"
    "a98365f841001ae3bba07ed9b430ef519b954cab8"
    "74b93e8d4f98786746e967eac019b8d6ba11f9a0b"
    "4ba4972b776d5729bf41760b585a7bdb30a2c49b5"
    "89c05f9f821d4396941b7ad3cc2420a1d8b91475a"
    "6c6442ace7ae5cd690be15230ed96556a8f402e3c"
    "eb152be817914f1b8e17a5bd7a4187cbc5c77ba51"
    "41997b72a0a84ec1f286b3770203010001"))

key = BLAKE2b.new(key=get_random_bytes(64), digest_bits=128).hexdigest().encode()
root = "b/"
extension = '.enc'
ignore = ['Windows']

#### Functions ####

def encrypt(data, key):
    cipher = AES.new(key, AES.MODE_OFB)
    data = binascii.hexlify(cipher.encrypt(data))
    data = binascii.hexlify(cipher.iv).decode() + '$' + data.decode()
    return data.encode()

def decrypt(data, key):
    data = data.decode().split("$")
    iv = binascii.unhexlify(data[0])
Exemplo n.º 21
0
async def openAccount(data):
    signature = data["signature"]
    address = data["address"]
    blockID = data["id"]

    valid = await verifySignature(signature, address, data)
    if not valid:
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "signature"
        }
        return toRespond

    preID = data.copy()
    preID.pop("signature")
    preID.pop("id")

    hasher = BLAKE2b.new(digest_bits=512)
    realID = hasher.update(json.dumps(preID).encode("utf-8")).hexdigest()
    if blockID != realID:
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "id"
        }
        return toRespond

    sendingAddress, sendingBlock = data["link"].split("/")
    sendingBlock = await getBlock(sendingAddress, sendingBlock)

    # Check that send block is valid
    valid = await verifySignature(sendingBlock["signature"], sendingAddress,
                                  sendingBlock)
    if not valid:
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "sendSignature"
        }
        return toRespond

    previousBlock = await getBlock(sendingAddress, sendingBlock["previous"])
    sendAmount = float(previousBlock["balance"]) - float(
        sendingBlock["balance"])

    if float(data["balance"]) != float(sendAmount):
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "invalidBalance"
        }

    elif data["previous"] != "0" * 20:
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "invalidPrevious"
        }

    else:
        response = {
            "type": "confirm",
            "action": "open",
            "address": f"{address}",
            "id": f"{blockID}"
        }

    return response
Exemplo n.º 22
0
async def receive(data):
    signature = data["signature"]
    address = data["address"]
    blockID = data["id"]

    valid = await verifySignature(signature, address, data)
    if not valid:
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "signature"
        }
        return toRespond

    preID = data.copy()
    preID.pop("signature")
    preID.pop("id")

    hasher = BLAKE2b.new(digest_bits=512)
    realID = hasher.update(json.dumps(preID).encode("utf-8")).hexdigest()
    if blockID != realID:
        toRespond = {
            "type": "rejection",
            "address": "{address}",
            "id": "{blockID}",
            "reason": "id"
        }
        return toRespond

    sendingAddress, sendingBlock = data["link"].split("/")
    sendingBlock = await getBlock(sendingAddress, sendingBlock)

    # Check that send block is valid
    valid = await verifySignature(sendingBlock["signature"], sendingAddress,
                                  sendingBlock)
    if not valid:
        toRespond = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "sendSignature"
        }
        return toRespond

    f = await aiofiles.open(f"{ledgerDir}{address}")
    blocks = await f.read()
    await f.close()
    blocks = blocks.splitlines()
    for block in blocks:
        if json.loads(block)["type"] == "genesis":
            continue

        if json.loads(block)["link"] == data["link"]:
            response = {
                "type": "rejection",
                "address": address,
                "id": blockID,
                "reason": "doubleReceive"
            }
            return response

    previousBlock = await getBlock(sendingAddress, sendingBlock["previous"])
    sendAmount = float(previousBlock["balance"]) - float(
        sendingBlock["balance"])

    head = await getHead(address)
    if float(data["balance"]) != float(head["balance"]) + float(sendAmount):
        print(data["balance"])
        print(float(head["balance"]) + float(sendAmount))
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "invalidBalance"
        }

    elif data["previous"] != head["id"]:
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "invalidPrevious"
        }

    else:
        response = {
            "type": "confirm",
            "action": "receive",
            "address": f"{address}",
            "id": f"{blockID}"
        }

    return response
Exemplo n.º 23
0
 def new(data=None):
     return BLAKE2b.new(digest_bits=512, data=data)
Exemplo n.º 24
0
 def __init__(self):
     self.hasher = BLAKE2b.new(digest_bits=256)
Exemplo n.º 25
0
    def testSignVerify(self):
        h = SHA1.new()
        h.update(b('blah blah blah'))

        class RNG(object):
            def __init__(self):
                self.asked = 0

            def __call__(self, N):
                self.asked += N
                return Random.get_random_bytes(N)

        key = RSA.generate(1024)

        # Helper function to monitor what's request from MGF
        global mgfcalls

        def newMGF(seed, maskLen):
            global mgfcalls
            mgfcalls += 1
            return bchr(0x00) * maskLen

        # Verify that PSS is friendly to all hashes
        for hashmod in (MD2, MD5, SHA1, SHA224, SHA256, SHA384, RIPEMD160):
            h = hashmod.new()
            h.update(b('blah blah blah'))

            # Verify that sign() asks for as many random bytes
            # as the hash output size
            rng = RNG()
            signer = PKCS.new(key, randfunc=rng)
            s = signer.sign(h)
            signer.verify(h, s)
            self.assertEqual(rng.asked, h.digest_size)

        # Blake2b has variable digest size
        for digest_bits in (160, 256, 384):  # 512 is too long
            hobj = BLAKE2b.new(digest_bits=digest_bits)
            hobj.update(b("BLAKE2b supports several digest sizes"))

            signer = PKCS.new(key)
            signature = signer.sign(hobj)
            signer.verify(hobj, signature)

        # Blake2s too
        for digest_bits in (128, 160, 224, 256):
            hobj = BLAKE2s.new(digest_bits=digest_bits)
            hobj.update(b("BLAKE2s supports several digest sizes"))

            signer = PKCS.new(key)
            signature = signer.sign(hobj)
            signer.verify(hobj, signature)

        h = SHA1.new()
        h.update(b('blah blah blah'))

        # Verify that sign() uses a different salt length
        for sLen in (0, 3, 21):
            rng = RNG()
            signer = PKCS.new(key, saltLen=sLen, randfunc=rng)
            s = signer.sign(h)
            self.assertEqual(rng.asked, sLen)
            signer.verify(h, s)

        # Verify that sign() uses the custom MGF
        mgfcalls = 0
        signer = PKCS.new(key, newMGF)
        s = signer.sign(h)
        self.assertEqual(mgfcalls, 1)
        signer.verify(h, s)

        # Verify that sign() does not call the RNG
        # when salt length is 0, even when a new MGF is provided
        key.asked = 0
        mgfcalls = 0
        signer = PKCS.new(key, newMGF, 0)
        s = signer.sign(h)
        self.assertEqual(key.asked, 0)
        self.assertEqual(mgfcalls, 1)
        signer.verify(h, s)
Exemplo n.º 26
0
async def send(data):
    signature = data["signature"]
    address = data["address"]
    blockID = data["id"]

    valid = await verifySignature(signature, address, data)
    if not valid:
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "signature"
        }
        return response

    preID = data.copy()
    preID.pop("signature")
    preID.pop("id")

    hasher = BLAKE2b.new(digest_bits=512)
    realID = hasher.update(json.dumps(preID).encode("utf-8")).hexdigest()
    head = await getHead(address)
    if blockID != realID:
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "id"
        }

    elif float(head["balance"]) < float(data["balance"]):
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "balance"
        }

    elif float(data["balance"]) < 0:
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "balance"
        }

    elif head["id"] != data["previous"]:
        response = {
            "type": "rejection",
            "address": f"{address}",
            "id": f"{blockID}",
            "reason": "invalidPrevious"
        }

    else:
        response = {
            "type": "confirm",
            "action": "send",
            "address": f"{address}",
            "id": f"{blockID}"
        }

    return response
Exemplo n.º 27
0
 def generateHash(self, data: bytes) -> str:
     ''' Returns the hash in hexadecimal string (with no 0x) format 
         given an object in Bytes.
     '''
     return BLAKE2b.new(digest_bits=256).update(data).hexdigest()
Exemplo n.º 28
0
 def new(data=None):
     return BLAKE2b.new(digest_bits=512, data=data)
Exemplo n.º 29
0
 def _common(self, raw: bytes):
     return BLAKE2b.new(data=raw,
                        digest_bits=self._digest_bits,
                        key=self._secret)
Exemplo n.º 30
0
def hash_pin(pin, salt):
    state = BLAKE2b.new()
    state.update(pin)
    state.update(salt)
    return state.digest()
Exemplo n.º 31
0
        def testSignVerify(self):
                        h = SHA1.new()
                        h.update(b('blah blah blah'))

                        class RNG(object):
                            def __init__(self):
                                self.asked = 0
                            def __call__(self, N):
                                self.asked += N
                                return Random.get_random_bytes(N)

                        key = RSA.generate(1024)

                        # Helper function to monitor what's request from MGF
                        global mgfcalls
                        def newMGF(seed,maskLen):
                            global mgfcalls
                            mgfcalls += 1
                            return bchr(0x00)*maskLen

                        # Verify that PSS is friendly to all hashes
                        for hashmod in (MD2,MD5,SHA1,SHA224,SHA256,SHA384,RIPEMD160):
                            h = hashmod.new()
                            h.update(b('blah blah blah'))

                            # Verify that sign() asks for as many random bytes
                            # as the hash output size
                            rng = RNG()
                            signer = PKCS.new(key, randfunc=rng)
                            s = signer.sign(h)
                            signer.verify(h, s)
                            self.assertEqual(rng.asked, h.digest_size)

                        # Blake2b has variable digest size
                        for digest_bits in (160, 256, 384):  # 512 is too long
                            hobj = BLAKE2b.new(digest_bits=digest_bits)
                            hobj.update(b("BLAKE2b supports several digest sizes"))

                            signer = PKCS.new(key)
                            signature = signer.sign(hobj)
                            signer.verify(hobj, signature)

                        # Blake2s too
                        for digest_bits in (128, 160, 224, 256):
                            hobj = BLAKE2s.new(digest_bits=digest_bits)
                            hobj.update(b("BLAKE2s supports several digest sizes"))

                            signer = PKCS.new(key)
                            signature = signer.sign(hobj)
                            signer.verify(hobj, signature)


                        h = SHA1.new()
                        h.update(b('blah blah blah'))

                        # Verify that sign() uses a different salt length
                        for sLen in (0,3,21):
                            rng = RNG()
                            signer = PKCS.new(key, saltLen=sLen, randfunc=rng)
                            s = signer.sign(h)
                            self.assertEqual(rng.asked, sLen)
                            signer.verify(h, s)

                        # Verify that sign() uses the custom MGF
                        mgfcalls = 0
                        signer = PKCS.new(key, newMGF)
                        s = signer.sign(h)
                        self.assertEqual(mgfcalls, 1)
                        signer.verify(h, s)

                        # Verify that sign() does not call the RNG
                        # when salt length is 0, even when a new MGF is provided
                        key.asked = 0
                        mgfcalls = 0
                        signer = PKCS.new(key, newMGF, 0)
                        s = signer.sign(h)
                        self.assertEqual(key.asked,0)
                        self.assertEqual(mgfcalls, 1)
                        signer.verify(h, s)
Exemplo n.º 32
0
async def main():
    global websocket
    uri = "ws://murraxcoin.murraygrov.es:6969"
    websocket = await websocketSecure.connect(uri)

    asyncio.create_task(websocketPoolLoop())

    await ping()

    resp = await wsRequest(
        f'{{"type": "balance", "address": "{publicKeyStr}"}}')
    resp = json.loads(resp)

    if resp["type"] != "rejection":
        balance = float(resp["balance"])

    else:
        balance = 0

    print(f"Balance: {balance}")
    req = {"type": "pendingSend", "address": publicKeyStr}
    resp = await wsRequest(json.dumps(req))
    resp = json.loads(resp)

    if resp["link"] != "":
        await receive(resp["sendAmount"], resp["link"])

    req = {"type": "watchForSends", "address": publicKeyStr}
    await wsRequest(json.dumps(req))

    while True:
        action = await ainput("Send or Delegate? (s/d) ")
        if action == "s":
            sendAddress = await ainput("Send Address: ")
            toSend = await ainput("Amount to send: ")
            toSend = int(toSend)

            resp = await wsRequest(
                f'{{"type": "balance", "address": "{publicKeyStr}"}}')
            resp = json.loads(resp)

            if resp["type"] != "rejection":
                balance = float(resp["balance"])

            else:
                balance = 0

            newBalance = balance - toSend

            response = await wsRequest(
                f'{{"type": "getPrevious", "address": "{publicKeyStr}"}}')
            previous = json.loads(response)["link"]

            response = await wsRequest(
                json.dumps({
                    "type": "getRepresentative",
                    "address": publicKeyStr
                }))
            representative = json.loads(response)["representative"]

            data = {
                "type": "send",
                "address": f"{publicKeyStr}",
                "link": f"{sendAddress}",
                "balance": f"{newBalance}",
                "previous": previous,
                "representative": representative
            }

            hasher = BLAKE2b.new(digest_bits=512)
            blockID = hasher.update(
                json.dumps(data).encode("utf-8")).hexdigest()
            data["id"] = blockID
            signature = await genSignature(data, privateKey)
            data = {**data, **{"signature": f"{signature}"}}
            resp = await wsRequest(json.dumps(data))
            if json.loads(resp)["type"] == "confirm":
                print("MXC send initiated!")

            else:
                print("MXC send failed to initiate, please see error below:")
                print(resp)

        elif action == "d":
            delegateAddress = await ainput("Delegate Address: ")
            response = await wsRequest(
                f'{{"type": "getPrevious", "address": "{publicKeyStr}"}}')
            previous = json.loads(response)["link"]

            data = {
                "type": "change",
                "address": publicKeyStr,
                "balance": balance,
                "representative": delegateAddress,
                "previous": previous
            }
            hasher = BLAKE2b.new(digest_bits=512)
            blockID = hasher.update(
                json.dumps(data).encode("utf-8")).hexdigest()
            data["id"] = blockID
            signature = await genSignature(data, privateKey)
            data["signature"] = signature

            resp = await wsRequest(json.dumps(data))
            if json.loads(resp)["type"] == "confirm":
                print("Delegation change initiated!")

            else:
                print(
                    "MXC delegation change failed to initiate, please see error below:"
                )
                print(resp)
from Crypto.PublicKey import RSA
from Crypto.Signature.pkcs1_15 import PKCS115_SigScheme
from Crypto.Hash import BLAKE2b
from hashlib import blake2b

import binascii

transaction = sys.argv[1]
name_file = sys.argv[2]
signature = sys.argv[3]

signature = binascii.unhexlify(signature.encode())

#importer des clés à partir d'un fichier
with open(name_file, 'r') as fp:
    pub = fp.read()
    fp.close()

public = RSA.importKey(pub)

print(public)
# Verify valid PKCS#1 v1.5 signature (RSAVP1)
hash = BLAKE2b.new()
hash.update(transaction.encode())
verifier = PKCS115_SigScheme(public)
try:
    verifier.verify(hash, signature)
    print("Signature is valid.")
except:
    print("Signature is invalid.")