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)
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
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))
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
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})
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
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))
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"))
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
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
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
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)
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)