Esempio n. 1
0
def base64decode_check(encoded):
    decoded = base64.b64decode(encoded)
    check = decoded[-4:]
    body = decoded[:-4]
    shaHash = sha256(sha256(body, encoder=nacl.encoding.RawEncoder),
                     encoder=nacl.encoding.RawEncoder)
    if shaHash[0:4] != check:
        raise ValueError('Invalid hash')
    return body
Esempio n. 2
0
    def round1_setup_packages_decode(pkgs, crypto, chksum_test=True):
        # Break apart the received setup package packet per the above method
        # and return the unencrypted data along with the cryptographic box
        # to perform this again
        plaintext, hash_pkgs, h_target = None, -1, -2
        box = None
        pkg_data,hash_data = [], []

        chksum = pkgs[0:64]
        
        if chksum_test and (not chksum == sha256(pkgs[64:])):
            raise Exception("Checksum does not match")
        
        cert_hex = pkgs[64:128]
        path_length = int(pkgs[128:130])
        pkg_size = int(pkgs[130:134])
        hash_size = int(pkgs[134:138])
        
        # Create a box
        box = crypto.public_box(PrivateKey(cert_hex, encoder=nacl.encoding.HexEncoder))
        
        # Now get the packages and hashes
        hash_start = 138+(path_length*pkg_size)
        for i in range(path_length):
            pkg_i = pkgs[138+(i*pkg_size):138+((i+1)*pkg_size)]
            hash_i = pkgs[hash_start+(i*hash_size):hash_start+((i+1)*hash_size)]
            pkg_data.append(pkg_i)
            hash_data.append(hash_i)

        # Attempt to decrypt the packages (and calculate the hash on other
        # encrypted packages) and decrypt the hashes one by one
        i = 0
        for pkg in pkg_data:
            try:
                plaintext = box.decrypt(pkg)
                s = None
                if i == path_length - 1:
                    s = ''.join(pkg_data[0:i])
                else:
                    s = ''.join(pkg_data[0:i]+pkg_data[i+1:path_length])
                h_target = sha256(s)
                break
            except:
                pass
            i += 1
                
        for h in hash_data:
            try:
                 hash_pkgs = box.decrypt(h)
                 break
            except:
                pass
        
        if hash_pkgs == h_target:
            return box, plaintext
        else:
            raise Exception("Hashes do not match")
Esempio n. 3
0
    def public_address(self):
        if self.__public_address == None:  # { generate if nessisary
            first = sha256(self.signing_key.verify_key.encode(), RawEncoder)
            double_sha = sha256(first, RawEncoder)

            # base64 encode, the take first 7 chars aka url and filename safe
            self.__public_address = base64_encode(double_sha, b'-_')[:7]
        # }

        return self.__public_address
def init(prefs, the_ephemeral_key, has=False):
    encrypted_prefs = []
    for pref in prefs:
        if not has:
            hashed_reciprocal_pref = sha256(reciprocal_map[pref])
            want_pref = c.crypto_scalarmult(the_ephemeral_key, hashed_reciprocal_pref)
            encrypted_prefs.append(want_pref)
        else:
            hashed_pref = sha256(pref)
            have_pref = c.crypto_scalarmult(the_ephemeral_key, hashed_pref)
            encrypted_prefs.append(have_pref)
    return encrypted_prefs
Esempio n. 5
0
def decrypt_message(encrypted_message, keying_material, private_key):
    encrypted_key = keying_material['encrypted_key']
    message_signature = keying_material['message_signature']
    temp_public_key = PublicKey(
        keying_material['temp_public_key'],
        Base64Encoder)

    box = PublicBox(private_key, temp_public_key)

    message_key = box.decrypt(
        encrypted_key,
        encoder=Base64Encoder)

    # We got the key, so let's get the message.
    message_box = nacl.secret.SecretBox(message_key)
    message = message_box.decrypt(
        encrypted_message,
        encoder=Base64Encoder)

    # Check the signature.
    mac_key = sha256(box._shared_key, RawEncoder)
    signing_key = SigningKey(mac_key)
    if signing_key.sign(message, Base64Encoder) != message_signature:
        raise SignatureError("The signature is not valid")

    return message
Esempio n. 6
0
    def create_genesis_block(genesis_key,
                             node_address,
                             public_key,
                             difficulty=1,
                             difficulty_mode=0):
        nonce = nacl.utils.random(16)
        public_key = public_key._public_key if isinstance(
            public_key, nacl.public.PublicKey) else public_key
        signature = genesis_key.sign(node_address + nonce + public_key)
        difficulty = difficulty if difficulty < 5 and difficulty > 0 else 1

        # mild PoW
        while not BasicBlockChain.meets_difficulty(
                signature.signature, difficulty, difficulty_mode):
            nonce = nacl.utils.random(16)
            signature = genesis_key.sign(node_address + nonce + public_key)

        hash = sha256(signature.signature, encoder=RawEncoder)

        # return the genesis block
        return {
            'block_height': 0,
            'hash': hash,
            'signature': signature.signature,
            'address': genesis_key.verify_key._key,
            'node_address': node_address,
            'nonce': nonce,
            'public_key': public_key
        }
Esempio n. 7
0
    def create_block(signing_key,
                     previous_block,
                     body,
                     difficulty=1,
                     difficulty_mode=0):
        signing_key = SigningKey(signing_key) if type(signing_key) == type(
            's') or type(signing_key) == type(b's') else signing_key
        nonce = nacl.utils.random(16)
        signature = signing_key.sign(previous_block['hash'] + nonce + body)

        # mild PoW
        while not BasicBlockChain.meets_difficulty(
                signature.signature, difficulty, difficulty_mode):
            nonce = nacl.utils.random(16)
            signature = signing_key.sign(previous_block['hash'] + nonce + body)

        hash = sha256(signature.signature, encoder=RawEncoder)

        # return the block
        return {
            'block_height': previous_block['block_height'] + 1,
            'hash': hash,
            'signature': signature.signature,
            'address': signing_key.verify_key._key,
            'previous_block': previous_block['hash'],
            'nonce': nonce,
            'body': body
        }
def storeRes(s, key, value):
    decr_res = nstp_v3_pb2.DecryptedMessage()
    store_res = nstp_v3_pb2.StoreResponse()
    print("hiii+++++", value)
    store_res.hash = hash.sha256(value)
    store_res.hash_algorithm = nstp_v3_pb2.HashAlgorithm.SHA256
    decr_res.store_response.CopyFrom(store_res)
    EncryptAndSend(s, decr_res)
Esempio n. 9
0
 def create_key(self, key_id=None):
     key = random(SecretBox.KEY_SIZE)
     if not key_id:
         h = sha256(key, HexEncoder)
         key_id = h.decode('utf-8')[:16]
     self.keys[key_id] = key
     log_debug("Key {} was created.".format(key_id))
     self.save_key(key_id)
     return key_id
Esempio n. 10
0
def hash_string(s):
    """
    Hash the input string and convert the result to string format.
    :param s: a string to hash
    :return: hash of the input string in string format.
    """
    b = s.encode('utf-8')
    h = sha256(b, HexEncoder)
    return h.decode('utf-8')
Esempio n. 11
0
 def from_leaves(cls,
                 leaves,
                 base=2,
                 hashfunc=lambda data: sha256(data, encoder=RawEncoder)):
     while len(leaves) % base > 0:
         leaves.append(null_node)
     levels = ceil(log(len(leaves), base)) + 1
     tree = cls(base, levels, hashfunc)
     tree.fill(leaves)
     return tree
Esempio n. 12
0
 def __init__(self,
              base,
              levels,
              hashfunc=lambda data: sha256(data, encoder=RawEncoder)):
     self.levels = levels
     self.base = base
     self.hashfunc = hashfunc
     # create an appropriate number of empty nodes for each level, from root to leaves
     for i in range(0, levels):
         t = [null_node for c in range(0, base**i)]
         self.append(t)
Esempio n. 13
0
    def verify(message,
               proof,
               hashfunc=lambda data: sha256(data, encoder=RawEncoder)):
        hash = hashfunc(message)
        working = deepcopy(proof)
        for i in range(len(proof) - 1):
            index = proof[i][0]
            del working[i][0]
            working[i].insert(index, hash)
            hash = hashfunc(b''.join(working[i]))

        return hash == proof[-1][0]
def pingRes(s, ping_req):
    ping_res = nstp_v3_pb2.PingResponse()
    if ping_req.hash_algorithm == nstp_v3_pb2.HashAlgorithm.IDENTITY:
        ping_res.hash = ping_req.data
    elif ping_req.hash_algorithm == nstp_v3_pb2.HashAlgorithm.SHA256:
        ping_res.hash = hash.sha256(ping_req.data)
    elif ping_req.hash_algorithm == nstp_v3_pb2.HashAlgorithm.SHA512:
        ping_res.hash = hash.sha512(ping_req.data)
    else:
        return
    decr_res = nstp_v3_pb2.DecryptedMessage()
    decr_res.ping_response.CopyFrom(ping_res)
    EncryptAndSend(s, decr_res)
Esempio n. 15
0
def neriapi(destinyid):
    if not sha256(
            bytes(request.headers.get('x-neriapi-key', 'missing'), 'utf-8'),
            encoder=HexEncoder
    ) == b'e3143238a43d9f1c12f47314a8c858a5589f1b2f5c174d391a0e361f869b1427':
        return jsonify(status=500, error='Wrong api key')
    discordID = loop.run_until_complete(lookupDiscordID(destinyid))
    if not discordID:
        return jsonify(status=500, error='Unknown destiny id')
    token = loop.run_until_complete(getToken(discordID))
    refresh_token = loop.run_until_complete(getRefreshToken(discordID))
    if not token:
        return jsonify(status=500, error='Token not found')
    return jsonify(status=200, token=token, refresh_token=refresh_token)
def key_test( msg='test',
		key_enc='pbb6wrDXlLWOFMXYH4a9YHh7nGGD1VnStVYQBe9MyVU=' ):
	from hashlib import sha256
	key = key_generate()
	assert key_sign_check(key_get_vk(key), msg, key_sign(key, msg))
	key = key_decode_sk(key_enc)
	key_vk = key_get_vk(key)
	sign = key_sign(key, msg)
	assert key_sign_check(key_vk, msg, sign)
	print(sha256(''.join([
		key_encode(key), key_encode(key_vk),
		key_encode(key_decode_vk(key_encode(key_vk))),
		key_get_id(key), key_get_id(key_vk),
		msg, sign ])).hexdigest())
Esempio n. 17
0
    def meets_difficulty(signature, difficulty=1, difficulty_mode=0):
        hash = sha256(signature, encoder=RawEncoder)

        if difficulty_mode == 0:
            # determines if the block hash has enough preceding null bytes
            for i in range(0, difficulty):
                if hash[i] > 0:
                    return False
        if difficulty_mode == 1:
            # determines if the block has enough repeating digits at end
            for i in range(1, difficulty + 1):
                if hash[-i] != hash[-1 - i]:
                    return False

        return True
Esempio n. 18
0
 def round1_setup_package(self):
     # To generate an output string we use the struct module that converts
     # the data into a c-style btye str/array
     #   See: http://docs.python.org/2/library/struct.html
     s = pack("<15s15sH64s32s32s64s64sBB", \
         self.prev_ip_addr, \
         self.next_ip_addr, \
         self.next_port, \
         self.path_construction_cert_hex, \
         self.prev_id, \
         self.next_id, \
         self.prev_path_building_cert_hex, \
         self.next_path_building_cert_hex, \
         self.type, \
         self.terminating, \
         )
     
     s += pack("<64s", sha256(s)) # append the hash of the decrypted package
         
     # TODO: Pack seeds and tuples
     return s
Esempio n. 19
0
def encrypt_message(message, identifier):
    """Encrypts a message so that it can be read by all the devices of the
    given identifier.

    :param message: the message itself, in clear text.
    :param identifier: the identifier of the message recipient.
    """
    # Cipher the message with a brand new random key.
    message_key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
    message_box = nacl.secret.SecretBox(message_key)
    message_nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
    encrypted_message = message_box.encrypt(message, message_nonce,
                                            Base64Encoder)

    returned = []
    # Encrypt the message key with each recipient's public key.
    for recipient_device_pub_key in get_public_keys(identifier):

        # Generate a new keypair & cipher the key with it.
        temp_private_key, temp_public_key = generate_keypair()
        box = PublicBox(temp_private_key, recipient_device_pub_key)
        nonce = nacl.utils.random(PublicBox.NONCE_SIZE)
        encrypted_key = box.encrypt(message_key, nonce, Base64Encoder)

        # Sign the message.
        mac_key = sha256(box._shared_key, RawEncoder)
        signing_key = SigningKey(mac_key)
        message_sig = signing_key.sign(message, Base64Encoder)

        # Return the public key used to cipher the message key.
        returned.append({
            'encrypted_key': encrypted_key,
            'temp_public_key': temp_public_key.encode(Base64Encoder),
            'message_signature': message_sig
        })

    return {
        'encrypted_message': encrypted_message,
        'recipients': returned
    }
Esempio n. 20
0
    def make_web_app(self):
        from flask import request
        from flask_sqlalchemy import SQLAlchemy

        # WSGI/Flask Service
        short_name = bytes(self.stamp).hex()[:6]
        self.rest_app = Flask(f"faucet-{short_name}",
                              template_folder=TEMPLATES_DIR)
        self.rest_app.config[
            'SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{self.db_filepath}'
        try:
            self.rest_app.secret_key = sha256(
                os.environ['NUCYPHER_FELIX_DB_SECRET'].encode())  # uses envvar
        except KeyError:
            raise OSError(
                "The 'NUCYPHER_FELIX_DB_SECRET' is not set.  Export your application secret and try again."
            )

        # Database
        self.db = SQLAlchemy(self.rest_app)

        # Database Tables
        class Recipient(self.db.Model):
            """
            The one and only table in Felix's database; Used to track recipients and airdrop metadata.
            """

            __tablename__ = 'recipient'

            id = self.db.Column(self.db.Integer, primary_key=True)
            address = self.db.Column(self.db.String,
                                     unique=True,
                                     nullable=False)
            joined = self.db.Column(self.db.DateTime,
                                    nullable=False,
                                    default=datetime.utcnow)
            total_received = self.db.Column(self.db.String,
                                            default='0',
                                            nullable=False)
            last_disbursement_amount = self.db.Column(self.db.String,
                                                      nullable=False,
                                                      default=0)
            last_disbursement_time = self.db.Column(self.db.DateTime,
                                                    nullable=True,
                                                    default=None)
            is_staking = self.db.Column(self.db.Boolean,
                                        nullable=False,
                                        default=False)

            def __repr__(self):
                return f'{self.__class__.__name__}(id={self.id})'

        self.Recipient = Recipient  # Bind to outer class

        # Flask decorators
        rest_app = self.rest_app
        limiter = Limiter(self.rest_app,
                          key_func=get_remote_address,
                          headers_enabled=True)

        #
        # REST Routes
        #

        @rest_app.route("/", methods=['GET'])
        @limiter.limit("100/day;20/hour;1/minute")
        def home():
            rendering = render_template(self.TEMPLATE_NAME)
            return rendering

        @rest_app.route("/register", methods=['POST'])
        @limiter.limit("5 per day")
        def register():
            """Handle new recipient registration via POST request."""
            try:
                new_address = request.form['address']
            except KeyError:
                return Response(status=400)  # TODO

            if not eth_utils.is_checksum_address(new_address):
                return Response(status=400)  # TODO

            if new_address in self.reserved_addresses:
                return Response(status=400)  # TODO

            try:
                with ThreadedSession(self.db_engine) as session:

                    existing = Recipient.query.filter_by(
                        address=new_address).all()
                    if existing:
                        # Address already exists; Abort
                        self.log.debug(f"{new_address} is already enrolled.")
                        return Response(status=400)

                    # Create the record
                    recipient = Recipient(address=new_address,
                                          joined=datetime.now())
                    session.add(recipient)
                    session.commit()

            except Exception as e:
                # Pass along exceptions to the logger
                self.log.critical(str(e))
                raise

            else:
                return Response(status=200)  # TODO

        return rest_app
	def key_get_id(key):
		if isinstance(key, SigningKey): key = key.verify_key
		return '{{:>{}s}}'.format(key_id_len).format(
			sha256(key.encode(), URLSafeBase64Encoder)[:key_id_len] )
Esempio n. 22
0
def hash_sha256(data: bytes):
    return sha256(data, encoder=HexEncoder)
Esempio n. 23
0
    def round1_setup_packages(self):
        # Generate a bunch of setup package data (strings)
        pkgs_and_nodes = []
        for node in self.nodes[1:-1]:
            pkg = node.round1_setup_package()
            pkg_encrypted = node.box.encryptn(pkg)
            # pkg_encrypted = node.encrypt_and_sign(pkg, self.path_construction_key)
            pkgs_and_nodes.append( (node, pkg_encrypted)) # append the node so we know the proper crypto keys
            
        # Shuffle the order of the setup packages
        shuffle(pkgs_and_nodes)
        pkgs = [x[1] for x in pkgs_and_nodes] # separate out pkgs
        
        # compute hash on (array - package) for each package (and shuffle)
        hashes = []
        for i in range(len(pkgs_and_nodes)):
            node = pkgs_and_nodes[i][0]
            s = None
            if i == len(pkgs) - 1:
                s = ''.join(pkgs[0:i])
            else:
                s = ''.join(pkgs[0:i]+pkgs[i+1:])
            
            h = node.box.encryptn(sha256(s))
            hashes.append(h)

        shuffle(hashes)
        
        # Format:
        # 0) 64 byte transmission checksum
        # 1) 64 byte cert (hex)
        # 2) 2 byte path length (N) 
        # 3) 4 byte package length (X)
        # 4) 4 byte hash length (Y)
        # 5) N packages of length X
        # 6) N packages of length Y
        
        # 1)
        pkg_str = self.my_node.path_building_cert_hex 
        
        # 2)
        s = str(self.length)
        while len(s) < 2: s = '0' + s
        pkg_str += s
        
        # 3)
        s = str(len(pkgs[0]))
        while len(s) < 4: s = '0' + s
        pkg_str += s
        
        # 4)
        s = str(len(hashes[0]))
        while len(s) < 4: s = '0' + s
        pkg_str += s
        
        # 5 and 6)
        for pkg in pkgs: pkg_str += pkg
        for h in hashes: pkg_str += h
        
        # 0)
        out = sha256(pkg_str) + pkg_str
        return out
Esempio n. 24
0
 def sha256(data):
     """Returns SHA256 digest"""
     #return hashlib.sha256(data).digest()
     return hash.sha256(data, encoder=encoding.HexEncoder)
Esempio n. 25
0
    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
    SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
    OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
    CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''

messages = [
    b'hello world', b'world hello', b'BTC', b'ETH', b'XLM', b'RawEncoder',
    b'encoder', b'sha256'
]
# messages = messages[0:-1]
# messages = messages[0:-4]
# messages = messages[0:-randint(1, 5)]
leaves = [
    sha256(messages[i], encoder=RawEncoder) for i in range(len(messages))
]

print("Messages: ", messages)
print()

print("MerkleTree:")
m = MerkleTree.from_leaves(leaves)  # base=2
# m = MerkleTree.from_messages(messages) # base=2
# m = MerkleTree.from_leaves(leaves, 3) # base=3
# m = MerkleTree.from_messages(messages, 5) # base=5
m.print_hex()
print()

index = randint(0, len(messages) - 1)
print("Proof that message ", messages[index], "(", str(hexlify(leaves[index])),
Esempio n. 26
0
def hash_(data):
    return sha256(data).decode('hex')
Esempio n. 27
0
 def from_messages(cls,
                   messages,
                   base=2,
                   hashfunc=lambda data: sha256(data, encoder=RawEncoder)):
     leaves = [hashfunc(messages[i]) for i in range(len(messages))]
     return cls.from_leaves(leaves, base, hashfunc)