Esempio n. 1
0
 def __init__(self, seed=None):
     if seed is None:
         seed = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
     else:
         seed = HexEncoder.decode(seed)
     public_key, secret_key = nacl.bindings.crypto_sign_seed_keypair(seed)
     self._public_key = HexEncoder.encode(public_key).decode()
     self._private_key = HexEncoder.encode(secret_key).decode()
     self._seed = HexEncoder.encode(seed).decode()
     self._signature_redeem = Protocol.public_key_to_signature_redeem(
         self._public_key)
     self._program_hash = Protocol.hex_string_to_program_hash(
         self._signature_redeem)
Esempio n. 2
0
def verify_signature(msg, signature, verify_key):
    # Encode the message to hex
    msg_hex = HexEncoder.encode(msg)
    # Decode signature to byte
    signature_bytes = HexEncoder.decode(signature)

    result = True
    try:
        verify_key.verify(msg_hex, signature_bytes, encoder=HexEncoder)
    except BadSignatureError:
        result = False
        pass

    return result
Esempio n. 3
0
    def test_hex_smessage_with_detached_sig_matches_with_attached_sig(self):
        sk = SigningKey.generate()
        vk = sk.verify_key

        smsg = sk.sign(b"Hello World in hex", encoder=HexEncoder)

        msg = smsg.message
        hexsig = smsg.signature

        sig = HexEncoder.decode(hexsig)

        assert vk.verify(msg, sig, encoder=HexEncoder) == \
            vk.verify(smsg, encoder=HexEncoder)

        assert HexEncoder.decode(msg) == b"Hello World in hex"
Esempio n. 4
0
    def test_hex_smessage_with_detached_sig_matches_with_attached_sig(self):
        sk = SigningKey.generate()
        vk = sk.verify_key

        smsg = sk.sign(b"Hello World in hex", encoder=HexEncoder)

        msg = smsg.message
        hexsig = smsg.signature

        sig = HexEncoder.decode(hexsig)

        assert vk.verify(msg, sig, encoder=HexEncoder) == \
            vk.verify(smsg, encoder=HexEncoder)

        assert HexEncoder.decode(msg) == b"Hello World in hex"
Esempio n. 5
0
def create_transaction(
    private_key: str, public_key: str, receiver: str, amount: int
) -> dict:
    """
    Creates a transaction from a sender's public key to a receiver's public key

    :param private_key: The Sender's private key
    :param public_key: The Sender's public key
    :param receiver: The Receiver's public key
    :param amount: The amount in cents
    :return: <dict> The transaction dict
    """

    tx = {
        "sender": public_key,
        "receiver": receiver,
        "amount": amount,
        "timestamp": int(time()),
    }
    tx_bytes = json.dumps(tx, sort_keys=True).encode("ascii")

    # Generate a signing key from the private key
    signing_key = SigningKey(private_key, encoder=HexEncoder)

    # Now add the signature to the original transaction
    signature = signing_key.sign(tx_bytes).signature
    tx["signature"] = HexEncoder.encode(signature).decode("ascii")

    return tx
Esempio n. 6
0
def make_bitcoin_keys_branched(password, salt, key_amount = 1, branches = [410]):
	'''
	Make multiple bitcoin private keys at once from any string
	Brances implements additional layer of security. Branch is better be an integer, but, for real, it may be any string
	Returns a list
	'''
	# password = sha000(password, 50)
	# salt = SHA256.new(password.encode()).digest()
	#print('salt',benc.encode(salt))
	count = int(str(int(benc.encode(salt),16))[0:5])

	master_key = PBKDF2(password, salt = str(salt), count=count) 
	
	def my_rand(n):
		my_rand.counter += 1
		return PBKDF2(master_key, "my_rand:%d" % my_rand.counter, dkLen=n, count=1)
	my_rand.counter = 0
	
	keys = []
	with progressbar.ProgressBar(max_value=key_amount) as bar_small:
		for tymes in range(key_amount):
			bar_small.update(tymes)
			key = PBKDF2(password,dkLen=64, salt = (str(salt) + str(branches[tymes%len(branches)])), count = count)
			#keys.append(ECC.generate(curve = 'P-256', randfunc=my_rand))
			keys.append(key.hex())
			password = key
	return list(enumerate(keys, start=1))
Esempio n. 7
0
def validate_transaction(tx: dict) -> bool:
    """
    Verifies that a given transaction was sent from the sender
    :param tx: The transaction dict
    :return: <bool>
    """

    public_key = tx["sender"]

    # We need to strip the "signature" key from the tx
    signature = tx.pop("signature")
    signature_bytes = HexEncoder.decode(signature)

    tx_bytes = json.dumps(tx, sort_keys=True).encode("ascii")

    # Generate a verifying key from the public key
    verify_key = VerifyKey(public_key, encoder=HexEncoder)

    # Attempt to verify the signature
    try:
        verify_key.verify(tx_bytes, signature_bytes)
    except BadSignatureError:
        return False
    else:
        return True
 def send_next_data(self, data):
     # type: (str) -> int
     # The length of the encrypted message is going to be longer than the
     #   actual payload length. HOWEVER, callers expect the length of the
     #   data that we sent as a result. The length of the data that we sent
     #   is the length of the data before encryption.
     len_data = len(data)
     encrypted_msg = self._box.encrypt(data, None)
     encoded_msg = HexEncoder.encode(encrypted_msg)
     self._conn.send_next_data(encoded_msg)
     return len_data
Esempio n. 9
0
    def __init__(self, name, private_key, data=None):
        self.name = name
        self.data = data or {}

        if isinstance(private_key, PrivateKey):
            self.private_key_obj = private_key
            self.private_key = private_key.encode().hex()
        else:
            self.private_key = private_key
            self.private_key_obj = PrivateKey(self.private_key, HexEncoder())

        self.secret_box = SecretBox(bytes.fromhex(self.private_key))
        self.boxes = {}
Esempio n. 10
0
    def test_valid_signed_message(self, _seed, public_key, message, signature,
                                  signed):
        key = VerifyKey(
            public_key,
            encoder=HexEncoder,
        )

        assert (binascii.hexlify(key.verify(signed,
                                            encoder=HexEncoder), ) == message)
        assert (binascii.hexlify(
            key.verify(message,
                       HexEncoder.decode(signature),
                       encoder=HexEncoder), ) == message)
Esempio n. 11
0
def get_credentials():
    if not current_user.is_authenticated:
        abort(403)
    user = "******".format(current_user)
    jid = user + "@chatproto.muikkuverkko.fi"

    timestamp = int(round(time() * 1000))
    payload = "{},{}".format(timestamp, user)
    signing_key = SigningKey(signing_key_hex, HexEncoder)
    signed = signing_key.sign(payload)
    password = signed.message + "," + HexEncoder.encode(signed.signature)

    sys.stderr.write("Outgoing password: {} \n".format(password))
    return jsonify({"jid": jid, "password": password})
Esempio n. 12
0
    def test_valid_signed_message(
            self, _seed, public_key, message, signature, signed):
        key = VerifyKey(
            public_key,
            encoder=HexEncoder,
        )

        assert binascii.hexlify(
            key.verify(signed, encoder=HexEncoder),
        ) == message
        assert binascii.hexlify(
            key.verify(message, HexEncoder.decode(signature),
                       encoder=HexEncoder),
        ) == message
Esempio n. 13
0
def generate_serval_keys(name):
    node_hash = HexEncoder.decode(nacl.hash.sha256(name.encode("utf-8")))
    sign_pk, sign_sk = crypto_sign_seed_keypair(node_hash)
    box_sk = crypto_sign_ed25519_sk_to_curve25519(sign_sk)
    box_pk = crypto_scalarmult_base(box_sk)

    rhiz_pk = HexEncoder.decode(nacl.hash.sha256(("rhizome"+name).encode("utf-8")))
    
    keys = {
        "sign_pk": HexEncoder.encode(sign_pk).decode("ascii").upper(),
        "box_sk":  HexEncoder.encode( box_sk).decode("ascii").upper(),
        "sign_sk": HexEncoder.encode(sign_sk).decode("ascii").upper(),
        "box_pk":  HexEncoder.encode( box_pk).decode("ascii").upper(),
        "sid":     HexEncoder.encode( box_pk).decode("ascii").upper(),
        "rhiz_pk": HexEncoder.encode(rhiz_pk).decode("ascii").upper(),
    }
    return keys
Esempio n. 14
0
def make_curve25519_keys_pbkdf2_branched(password, salt, key_amount = 1, branches = [410]):
	'''
	Make multiple key pairs at once, eather P-256 or curve25519 from any string.
	Brances implements additional layer of security. Branch is better be an integer, but, for real, it may be any string
	Returns a list
	'''
	# password = sha000(password, 50)
	# salt = SHA256.new(password.encode()).digest()
	#print('salt',benc.encode(salt))
	count = int(str(int(benc.encode(salt),16))[0:5])

	dkLen = 32
	
	keys = []
	with progressbar.ProgressBar(max_value=key_amount) as bar_small:
		for tymes in range(key_amount):
			bar_small.update(tymes)
			#sha256 = SHA256.new(password)
			#count = int(str(int(benc.encode(sha256.digest()),16))[0:5])
			#print(branches[tymes%len(branches)])
			key = PBKDF2(password, salt = (str(salt) + str(branches[tymes%len(branches)])), dkLen = dkLen, count = count)
			keys.append(PrivateKey(benc.encode(key), encoder=benc))
			password = key
	return list(enumerate(keys, start=1))	
Esempio n. 15
0
def read_config() -> Config:
    config = Config()
    try:
        with open(CONFIG_FILENAME) as f:
            obj = toml.load(f)

        def read(key: str, t: Type[T]) -> Optional[T]:
            ret = obj.get(key)
            return ret if isinstance(ret, t) else None

        temp = read("server_public_key", str)
        if temp:
            config.server_verify_key = VerifyKey(HexEncoder.decode(temp))
        temp = read("secret_key", str)
        if temp:
            config.signing_key = SigningKey(HexEncoder.decode(temp))
        config.initial_setup_nickname = read("initial_setup_nickname", str)
        config.server_address = read("server_address", str)
    except FileNotFoundError:
        pass
    except Exception:
        print(f"Malformed configuration file {CONFIG_FILENAME}.\n")
        raise
    return config
Esempio n. 16
0
def run_vouch(magic: str) -> None:
    try:
        vouch_data = base64.b64decode(magic.encode("utf-8"))
        verify_key = VerifyKey(vouch_data[:32])
        signed_nickname = vouch_data[32:]
        msg = verify_with_magic(b"NAME", verify_key, signed_nickname)
        nickname = msg.decode("utf-8")
    except Exception:
        print("Could not parse data!")
        sys.exit(1)

    try:
        config = read_config()
        port = connect(config)
        port.send_json(
            {
                "method": "vouch",
                "who": verify_key.encode(HexEncoder).decode("utf-8"),
                "signed_name": HexEncoder.encode(signed_nickname).decode("utf-8"),
            }
        )
        port.receive_json()
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

    if not ask(f"Grant permuter server access to {nickname}", default=True):
        return

    try:
        port.send_json({})
        port.receive_json()
    except Exception as e:
        print(f"Failed to grant access: {e}")
        sys.exit(1)

    assert config.server_address, "checked by connect"
    assert config.server_verify_key, "checked by connect"
    data = config.server_verify_key.encode() + config.server_address.encode("utf-8")
    token = SealedBox(verify_key.to_curve25519_public_key()).encrypt(data)
    print("Granted!")
    print()
    print("Send them the following token:")
    print(base64.b64encode(token).decode("utf-8"))
Esempio n. 17
0
def validate_signature(chain: str, web3, user_id: int, associated_wallet: str,
                       signature: str):
    if chain == "eth":
        signed_wallet = recover_user_id_hash(web3, user_id, signature)
        return signed_wallet == associated_wallet
    if chain == "sol":
        try:
            message = f"AudiusUserID:{user_id}"
            verify_key = VerifyKey(
                base58.b58decode(bytes(associated_wallet, "utf-8")))
            # Verify raises an error if the message is tampered w/ else returns the original msg
            verify_key.verify(str.encode(message),
                              HexEncoder.decode(signature))
            return True
        except Exception as e:
            logger.error(
                f"index.py | users.py | Verifying SPL validation signature for user_id {user_id} {e}",
                exc_info=True,
            )
            return False
    return False
Esempio n. 18
0
        password = sha000(password + paper, 50)

        salt = SHA256.new(password.encode()).digest()

        keys = make_me_keys(password  = password, salt = salt,\
             type = key_type, key_amount = key_number, \
             size_rsa = rsa_size, branches = branches)
        #print('keys', keys)
        key = dict(keys)[key_number]
        all_the_keys.append(key)

decoded_keys_temp_list = []

for the_key in all_the_keys:
    if key_type == 'curve25519':
        sec = benc.encode(the_key.__bytes__()).decode()
        pub = benc.encode(the_key.public_key.__bytes__()).decode()
        decoded_keys_temp_list.append({'secret': sec, 'public': pub})

    elif key_type == 'P-256':
        sec = the_key.export_key(format='PEM')
        pub = the_key._export_public_pem(compress=0)  #PEM
        decoded_keys_temp_list.append({'secret': sec, 'public': pub})

    elif key_type == 'RSA':
        sec = the_key.export_key().decode()
        pub = the_key.publickey().export_key().decode()
        decoded_keys_temp_list.append({'secret': sec, 'public': pub})

    elif key_type == 'bitcoin':
        from bitcoin import encode_privkey, privkey_to_address
Esempio n. 19
0
    intf = 'wlan0'
    intf_ip = subprocess.getoutput("ip address show dev " + intf).split()
    intf_ip = intf_ip[intf_ip.index('inet') + 1].split('/')[0]

    from firebase import firebase
    firebase = firebase.FirebaseApplication('https://pysnac.firebaseio.com',
                                            None)

    littleboyIP = firebase.put(url='https://pysnac.firebaseio.com',
                               name='/littleboy/ip',
                               data=intf_ip)
    fatmanIP = firebase.get('/fatman/ip', None)

    skbob = PrivateKey.generate()
    pkbob = skbob.public_key
    pkalice = HexEncoder.encode(bytes(pkbob))
    frozen = jsonpickle.encode(pkalice)
    firebase.put(url='https://pysnac.firebaseio.com',
                 name='/littleboy/pk',
                 data=frozen)
    nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
    nonce2 = nacl.utils.random(Box.NONCE_SIZE)
    nonceInt = int.from_bytes(nonce, byteorder='little')
    if (not (nonceInt % 2) == 1):
        nonceInt = nonceInt + 1
        nonce = nonceInt.to_bytes(24, byteorder='little')

    RECORD_SECONDS = 80000
    FORMAT = pyaudio.paInt16

    #opus constants
Esempio n. 20
0
 def sign(self, message):
     sig = nacl.bindings.crypto_sign(message,
                                     HexEncoder.decode(self._private_key))
     return sig[:64]  # length > 64, so cut 64
Esempio n. 21
0
def check(sign, msg):
    try:
        verify.verify(msg, HexEncoder.decode(sign))
        return True
    except BadSignatureError:
        return False
Esempio n. 22
0
with open(fileName) as jsonFile:
    txList = json.load(jsonFile)

# Get the first
firstTX = txList[0]

firstTX['input'] = fixPKInput(firstTX['input'])
firstTX['output'] = fixPKOutput(firstTX['output'])

firstTX = Transaction(firstTX['number'], firstTX['input'], firstTX['output'],
                      firstTX['sig'])

# Hash of arbitrary data for prev and nonce
prev = H(b'Hello ').hexdigest()
pow = H(b'World!').hexdigest()
nonce = HexEncoder.encode(b'Hello World!')

# create the genesis block
genesis = Block(firstTX, prev, nonce, pow)

threadID = 0
threads = []
# Create all of the broadcast queues
while threadID < numNodes:
    broadcastQueue.append(queue.Queue())
    threadID += 1

threadID = 0
while threadID < numNodes:
    #place holder for actual node constructor
    node = Node(genesis)
Esempio n. 23
0
 def get_box(self, other_public_key):
     if other_public_key not in self.boxes:
         opk = PublicKey(other_public_key, HexEncoder())
         self.boxes[other_public_key] = Box(self.private_key_obj, opk)
     return self.boxes[other_public_key]
Esempio n. 24
0
def fixPKInput(input):
    for ele in input:
        out = ele['output']
        out['pubkey'] = HexEncoder.decode(out['pubkey'])
    return input
Esempio n. 25
0
    def send_obj(self, message_obj):

        msg_json = message_obj.serialize()
        encrypted_msg = self._box.encrypt(msg_json, None)
        encoded_msg = HexEncoder.encode(encrypted_msg)
        self._conn.send_next_data(encoded_msg)
Esempio n. 26
0
def fixPKOutput(output):
    for ele in output:
        ele['pubkey'] = HexEncoder.decode(ele['pubkey'])
    return output