Ejemplo n.º 1
0
def getPoolTxnData(nodeAndClientInfoFilePath, poolId, newPoolTxnNodeNames):
    data={}
    data["seeds"]={}
    data["txns"]=[]
    for index, n in enumerate(newPoolTxnNodeNames, start=1):
        newStewardAlias = poolId + "Steward" + str(index)
        stewardSeed = (newStewardAlias + "0" * (32 - len(newStewardAlias))).encode()
        data["seeds"][newStewardAlias] = stewardSeed
        stewardSigner = SimpleSigner(seed=stewardSeed)
        data["txns"].append({
                TARGET_NYM: stewardSigner.verkey,
                ROLE: STEWARD, TXN_TYPE: NYM,
                ALIAS: poolId + "Steward" + str(index),
                TXN_ID: sha256("{}".format(stewardSigner.verkey).encode()).hexdigest()
        })

        newNodeAlias = n
        nodeSeed = (newNodeAlias + "0" * (32 - len(newNodeAlias))).encode()
        data["seeds"][newNodeAlias] = nodeSeed
        nodeSigner = SimpleSigner(seed=nodeSeed)
        data["txns"].append({
                TARGET_NYM: nodeSigner.verkey,
                TXN_TYPE: NODE,
                f.IDENTIFIER.nm: stewardSigner.verkey,
                DATA: {
                    CLIENT_IP: "127.0.0.1",
                    ALIAS: newNodeAlias,
                    NODE_IP: "127.0.0.1",
                    NODE_PORT: genHa()[1],
                    CLIENT_PORT: genHa()[1],
                    SERVICES: [VALIDATOR],
                },
                TXN_ID: sha256("{}".format(nodeSigner.verkey).encode()).hexdigest()
        })
    return data
Ejemplo n.º 2
0
def getPoolTxnData(nodeAndClientInfoFilePath, poolId, newPoolTxnNodeNames):
    data={}
    data["seeds"]={}
    data["txns"]=[]
    for index, n in enumerate(newPoolTxnNodeNames, start=1):
        newStewardAlias = poolId + "Steward" + str(index)
        stewardSeed = (newStewardAlias + "0" * (32 - len(newStewardAlias))).encode()
        data["seeds"][newStewardAlias] = stewardSeed
        stewardSigner = SimpleSigner(seed=stewardSeed)
        data["txns"].append({
                TARGET_NYM: stewardSigner.verkey,
                ROLE: STEWARD, TXN_TYPE: NYM,
                ALIAS: poolId + "Steward" + str(index),
                TXN_ID: sha256("{}".format(stewardSigner.verkey).encode()).hexdigest()
        })

        newNodeAlias = n
        nodeSeed = (newNodeAlias + "0" * (32 - len(newNodeAlias))).encode()
        data["seeds"][newNodeAlias] = nodeSeed
        nodeSigner = SimpleSigner(seed=nodeSeed)
        data["txns"].append({
                TARGET_NYM: nodeSigner.verkey,
                TXN_TYPE: NODE,
                f.IDENTIFIER.nm: stewardSigner.verkey,
                DATA: {
                    CLIENT_IP: "127.0.0.1",
                    ALIAS: newNodeAlias,
                    NODE_IP: "127.0.0.1",
                    NODE_PORT: genHa()[1],
                    CLIENT_PORT: genHa()[1],
                    SERVICES: [VALIDATOR],
                },
                TXN_ID: sha256("{}".format(nodeSigner.verkey).encode()).hexdigest()
        })
    return data
Ejemplo n.º 3
0
    def _hash_password(cls, password):
        salt = sha256()
        salt.update(os.urandom(60))
        salt = salt.hexdigest()

        hashed_pass = sha256()
        # Make sure password is a str because we cannot hash unicode objects
        hashed_pass.update((password + salt).encode('utf-8'))
        hashed_pass = hashed_pass.hexdigest()

        password = salt + hashed_pass
        return password
Ejemplo n.º 4
0
def getPoolTxnData(poolId, newPoolTxnNodeNames):
    data = {}
    data["seeds"] = {}
    data["txns"] = []
    data['nodesWithBls'] = {}
    for index, n in enumerate(newPoolTxnNodeNames, start=1):
        newStewardAlias = poolId + "Steward" + str(index)
        stewardSeed = (newStewardAlias + "0" *
                       (32 - len(newStewardAlias))).encode()
        data["seeds"][newStewardAlias] = stewardSeed
        stewardSigner = SimpleSigner(seed=stewardSeed)
        data["txns"].append({
            TARGET_NYM:
            stewardSigner.verkey,
            ROLE:
            STEWARD,
            TXN_TYPE:
            NYM,
            ALIAS:
            poolId + "Steward" + str(index),
            TXN_ID:
            sha256("{}".format(stewardSigner.verkey).encode()).hexdigest()
        })

        newNodeAlias = n
        nodeSeed = (newNodeAlias + "0" * (32 - len(newNodeAlias))).encode()
        data["seeds"][newNodeAlias] = nodeSeed
        nodeSigner = SimpleSigner(seed=nodeSeed)
        node_txn = {
            TARGET_NYM: nodeSigner.verkey,
            TXN_TYPE: NODE,
            f.IDENTIFIER.nm: stewardSigner.verkey,
            DATA: {
                CLIENT_IP: "127.0.0.1",
                ALIAS: newNodeAlias,
                NODE_IP: "127.0.0.1",
                NODE_PORT: genHa()[1],
                CLIENT_PORT: genHa()[1],
                SERVICES: [VALIDATOR],
            },
            TXN_ID:
            sha256("{}".format(nodeSigner.verkey).encode()).hexdigest()
        }

        _, bls_key = create_default_bls_crypto_factory().generate_bls_keys(
            seed=data['seeds'][n])
        node_txn[DATA][BLS_KEY] = bls_key
        data['nodesWithBls'][n] = True

        data["txns"].append(node_txn)

    return data
Ejemplo n.º 5
0
def test_auth_rule_for_hash_attrib_works(looper,
                                         sdk_wallet_trustee,
                                         sdk_pool_handle,
                                         sdk_user_wallet_a,
                                         sdk_wallet_trust_anchor):
    _, did_cl = sdk_user_wallet_a

    set_attrib_auth_to_none(looper, sdk_wallet_trustee, sdk_pool_handle)

    # We can add and modify attribs
    data = sha256(json.dumps({'name': 'John'}).encode()).hexdigest()
    sdk_add_attribute_and_check(looper, sdk_pool_handle, sdk_wallet_trust_anchor, None, did_cl, xhash=data)

    sdk_add_attribute_and_check(looper, sdk_pool_handle, sdk_wallet_trust_anchor, None, did_cl, xhash=data)

    sdk_send_and_check_auth_rule_request(looper,
                                         sdk_wallet_trustee,
                                         sdk_pool_handle,
                                         auth_action=EDIT_PREFIX,
                                         auth_type=ATTRIB,
                                         field='*',
                                         new_value='*',
                                         old_value='*',
                                         constraint=AuthConstraint(role=STEWARD, sig_count=1).as_dict)

    # We still can add, but cannot edit attrib
    data = sha256(json.dumps({'name': 'Ned'}).encode()).hexdigest()

    sdk_add_attribute_and_check(looper, sdk_pool_handle, sdk_wallet_trust_anchor, None, did_cl, xhash=data)

    with pytest.raises(RequestRejectedException) as e:
        sdk_add_attribute_and_check(looper, sdk_pool_handle, sdk_wallet_trust_anchor, None, did_cl, xhash=data)
    e.match('Not enough STEWARD signatures')

    sdk_send_and_check_auth_rule_request(looper,
                                         sdk_wallet_trustee,
                                         sdk_pool_handle,
                                         auth_action=ADD_PREFIX,
                                         auth_type=ATTRIB,
                                         field='*',
                                         new_value='*',
                                         constraint=AuthConstraint(role=STEWARD, sig_count=1).as_dict)
    # We cannot add or edit attrib
    data = sha256(json.dumps({'name': 'Aria'}).encode()).hexdigest()

    with pytest.raises(RequestRejectedException) as e:
        sdk_add_attribute_and_check(looper, sdk_pool_handle, sdk_wallet_trust_anchor, None, did_cl, xhash=data)
    e.match('Not enough STEWARD signatures')

    with pytest.raises(RequestRejectedException) as e:
        sdk_add_attribute_and_check(looper, sdk_pool_handle, sdk_wallet_trust_anchor, None, did_cl, xhash=data)
    e.match('Not enough STEWARD signatures')
Ejemplo n.º 6
0
def is_checksum_address(value: str) -> bool:
    if len(value) != 34:
        return False

    address = base58.b58decode(value)
    if len(address) != 25:
        return False

    if address[0] != 0x41:
        return False

    check_sum = sha256(sha256(address[:-4]).digest()).digest()[:4]
    if address[-4:] == check_sum:
        return True
Ejemplo n.º 7
0
    def is_address(self, address):
        """Helper function that will check if a given address is valid.

        Args:
            address (str): Address to validate if it's a proper TRON address.

        """
        if not isinstance(address, str):
            return False

        if len(address) == 42:
            address = self.address.from_hex(address).decode('utf8')

        bc = base58.b58decode(address)
        return bc[-4:] == sha256(sha256(bc[:-4]).digest()).digest()[:4]
Ejemplo n.º 8
0
def sha_hash(string) -> str:
    """
    Simplifies making a SHA 256 digest with a hash
    :param string: to hash
    :return: hashed str
    """
    return str(sha256((string + HASH_SALT).encode()).hexdigest())
Ejemplo n.º 9
0
 def login_user(self, email, password):
     return """MATCH (u:User) 
     WHERE u.email = "{email}" AND u.password = "******" 
     RETURN u.email as email, id(u) as user_id""".format(
         email=email,
         password=sha256(password.encode('utf-8')).hexdigest()
     )
 def OnButtonCheck1(self, event):
     src = str(self.inputN.GetValue().encode('utf8'))
     m1 = md5.new()   
     m1.update(src)
     self.Md5.SetValue(m1.hexdigest().decode('utf8'))
     
     m2 = _sha.new()   
     m2.update(src)   
     self.sha1.SetValue(m2.hexdigest().decode('utf8'))
     
     m3 = _sha256.sha224()
     m3.update(src)   
     self.sha224.SetValue(m3.hexdigest().decode('utf8'))
     
     m4 = _sha256.sha256()
     m4.update(src)   
     self.sha256.SetValue(m4.hexdigest().decode('utf8'))
     
     m5 = _sha512.sha384()
     m5.update(src) 
     self.sha384.SetValue(m5.hexdigest().decode('utf8'))  
     
     m6 = _sha512.sha512() 
     m6.update(src)   
     self.sha512.SetValue(m6.hexdigest().decode('utf8'))
Ejemplo n.º 11
0
    def OnButtonCheckED(self, event):
        c = 'utf8'
        dlg = str(self.inputD.GetValue())
        with open(dlg, 'rb') as EDfile:
            p = EDfile.read()
        src = str(p)
        m1 = md5.new()
        m1.update(src)
        self.Md5.SetValue(m1.hexdigest().decode(c))

        m2 = _sha.new()
        m2.update(src)
        self.sha1.SetValue(m2.hexdigest().decode(c))

        m3 = _sha256.sha224()
        m3.update(src)
        self.sha224.SetValue(m3.hexdigest().decode(c))

        m4 = _sha256.sha256()
        m4.update(src)
        self.sha256.SetValue(m4.hexdigest().decode(c))

        m5 = _sha512.sha384()
        m5.update(src)
        self.sha384.SetValue(m5.hexdigest().decode(c))

        m6 = _sha512.sha512()
        m6.update(src)
        self.sha512.SetValue(m6.hexdigest().decode(c))
Ejemplo n.º 12
0
def post_login(args):
    loaded_user = load_user(args['username'])
    if loaded_user.password == sha256(args['password']).hexdigest():
        login_user(loaded_user)
    else:
        flash('Username or Password is invalid', 'error')
    return index()
Ejemplo n.º 13
0
    def get_genesis_block(self, tx_context, channel_name):
        """get the genesis block of the channel

        :return: the genesis block in success or None in fail
        :rtype: Block/None
        """
        _logger.info("get genesis block - start")

        seek_info = create_seek_info(0, 0)

        kwargs = {}
        if self._client_cert_path:
            with open(self._client_cert_path, 'rb') as f:
                b64der = pem_to_der(f.read())
                kwargs['tls_cert_hash'] = sha256(b64der).digest()

        seek_info_header = build_channel_header(
            common_pb2.HeaderType.Value('DELIVER_SEEK_INFO'), tx_context.tx_id,
            channel_name, current_timestamp(), tx_context.epoch, **kwargs)

        seek_header = build_header(tx_context.identity, seek_info_header,
                                   tx_context.nonce)

        seek_payload_bytes = create_seek_payload(seek_header, seek_info)
        sig = tx_context.sign(seek_payload_bytes)
        envelope = create_envelope(sig, seek_payload_bytes)

        # this is a stream response
        return self.delivery(envelope)
Ejemplo n.º 14
0
 def address(self):
     """
     生成地址
     :return:
     """
     h = sha256(self._public_key.to_pem())
     return base64.b64encode(h.digest())
Ejemplo n.º 15
0
 def make_state_path_for_attr(did, attr_name, attr_is_hash=False) -> bytes:
     nameHash = sha256(
         attr_name.encode()).hexdigest() if not attr_is_hash else attr_name
     return "{DID}:{MARKER}:{ATTR_NAME}" \
         .format(DID=did,
                 MARKER=MARKER_ATTR,
                 ATTR_NAME=nameHash).encode()
Ejemplo n.º 16
0
def view_change_digest(msg: ViewChange) -> str:
    msg_as_dict = msg.__dict__
    msg_as_dict['checkpoints'] = [
        cp.__dict__ for cp in msg_as_dict['checkpoints']
    ]
    serialized = JsonSerializer().dumps(msg_as_dict)
    return sha256(serialized).hexdigest()
 def OnButtonCheckED(self, event):
     c = 'utf8'
     dlg = str(self.inputD.GetValue())
     with open(dlg,'rb') as EDfile:
         p = EDfile.read()
     src = str(p)
     m1 = md5.new()   
     m1.update(src)
     self.Md5.SetValue(m1.hexdigest().decode(c))
     
     m2 = _sha.new()   
     m2.update(src)   
     self.sha1.SetValue(m2.hexdigest().decode(c))
     
     m3 = _sha256.sha224()
     m3.update(src)   
     self.sha224.SetValue(m3.hexdigest().decode(c))
     
     m4 = _sha256.sha256()
     m4.update(src)   
     self.sha256.SetValue(m4.hexdigest().decode(c))
     
     m5 = _sha512.sha384()
     m5.update(src) 
     self.sha384.SetValue(m5.hexdigest().decode(c))  
     
     m6 = _sha512.sha512() 
     m6.update(src)   
     self.sha512.SetValue(m6.hexdigest().decode(c))
Ejemplo n.º 18
0
def get_authorization():
    android_id = mcdutils.get_random_android_id()
    username = mcdutils.generate_username(android_id)
    password = mcdutils.generate_password(android_id)
    vmob = mcdutils.generate_vmob_uid(android_id)

    data = {
        'username': username,
        'password': password,
        'grant_type': 'password'
    }
    data_json = json.dumps(data)
    digest = b64encode(sha256(data_json.encode()).digest()).decode()

    headers = mcdutils.get_headers(vmob)
    headers['Digest'] = 'SHA-256=' + digest

    r = requests.post('https://dif-dot-prd-euw-gmal-mcdonalds.appspot.com/plexure/v1/con/v3/DeviceRegistration',
                      data=data_json, headers=headers)

    if r.status_code != 200:
        print(r.status_code)
        print(r.content)
        return utils.request_error(r)

    x = json.loads(r.content.decode())
    headers['Authorization'] = '{} {}'.format(x['token_type'], x['access_token'])

    return headers
Ejemplo n.º 19
0
def main():
    experiment_save_dir = r"C:\Users\janul\Desktop\thesis_tmp_files\responses"

    requests = get_queries()

    exps = [experiments(i) for i in [58, 59, 60]]

    for exp in exps:
        try:
            print(exp.__repr__())
            if not exp:
                continue
            filename_hash = sha256(repr(exp).encode('utf-8')).hexdigest()
            responses_save_path = Path(experiment_save_dir, filename_hash).with_suffix(".npz")
            if (responses_save_path.exists()):
                print("Results already present.", responses_save_path)
                continue

            print("Output path:", responses_save_path)

            responses = exp.run(requests)
            FileStorage.save_data(responses_save_path, responses=responses, experiment=exp.__dict__, exp_repr=repr(exp),
                                  model=repr(exp.get_env().model), num_images=exp.num_images())
        except Exception:
            continue
Ejemplo n.º 20
0
def doSignIn():
    print(request.get_json())
    user = request.get_json()[u'sign_in_name'].encode('ascii')
    password = request.get_json()[u'sign_in_password'].encode('ascii')
    # user = do_xor(user)
    # password = do_xor(user)
    user = str(user)
    password = str(password)

    m = sha256()
    m.update(user.encode())
    m.update(password.encode())
    info = m.hexdigest()

    # compare input sha with stored sha
    if os.path.isfile('userInfo.txt'):
        with open('userInfo.txt', 'r') as secret:
            line = secret.readline()
            while line:
                if info == line.strip():
                    session['logged_in'] = True
                    session['username'] = user
                    session['startPos'] = 0
                    return json.dumps({'status': 'OK'})
                line = secret.readline()
    return json.dumps({'status': 'FAIL'})
Ejemplo n.º 21
0
    def OnButtonCheck1(self, event):
        src = str(self.inputN.GetValue().encode('utf8'))
        m1 = md5.new()
        m1.update(src)
        self.Md5.SetValue(m1.hexdigest().decode('utf8'))

        m2 = _sha.new()
        m2.update(src)
        self.sha1.SetValue(m2.hexdigest().decode('utf8'))

        m3 = _sha256.sha224()
        m3.update(src)
        self.sha224.SetValue(m3.hexdigest().decode('utf8'))

        m4 = _sha256.sha256()
        m4.update(src)
        self.sha256.SetValue(m4.hexdigest().decode('utf8'))

        m5 = _sha512.sha384()
        m5.update(src)
        self.sha384.SetValue(m5.hexdigest().decode('utf8'))

        m6 = _sha512.sha512()
        m6.update(src)
        self.sha512.SetValue(m6.hexdigest().decode('utf8'))
    def testgetINetpayQRCode(self):
        strdict = {
            "msgType": "unionpay.preCreate",
            "tipType": "percent",
            "requestTimestamp": self.now_time,
            "msgSrc": "IULINK",
            "mid": "123456789012345",
            "feeType": "156",
            "tid": "88880001",
            "transactionAmount": "11",
            "tipPercentage": "10.9",
            "qrcType": "11"
        }

        voiddigest = ""
        for key in sorted(strdict):
            voiddigest = voiddigest + key + "=" + strdict.get(key) + '&'

        print(voiddigest[:-1])
        voiddigest = voiddigest[:-1] + self.signkey

        strdict.setdefault("sign",
                           sha256(voiddigest.encode('utf-8')).hexdigest())
        response = requests.request("POST", self.url, data=str(strdict))

        print(response.text)
        img = qrcode.make(response.json().get("qrCodeContent"))
        img.save("./inetpay-unionpaycode.png")
        Image.open("./inetpay-unionpaycode.png").resize((360, 360)).show()
Ejemplo n.º 23
0
 def sign(self,message):
     """
     生成数字签名
     :param message:
     :return:
     """
     h = sha256(str(message).encode('utf-8'))
     return binascii.hexlify(self._private_key.sign(h.digest()))
Ejemplo n.º 24
0
 def verify_sign(self, pubkey,message,signature):
     """
     验证数字签名
     :return:
     """
     verifier = VerifyingKey.from_pem(pubkey)
     h = sha256(str(message).encode('utf-8'))
     return verifier.verify(binascii.unhexlify(signature), h.digest())
Ejemplo n.º 25
0
def compute_hash(object):
    """
    Generates a hash of a string
    :return:
    """
    tx_string = json.dumps(object.__dict__, sort_keys=True)

    return sha256(tx_string.encode()).hexdigest()
    def _download(self, url, dstfile, checksum):
        request.urlretrieve(url, dstfile)
        m = sha256()
        with open(dstfile, 'rb') as f:
            hash = m.update(f.read())

        if checksum != m.hexdigest():
            raise RuntimeError('Checksum of %s does not match!' % dstfile)
Ejemplo n.º 27
0
 def hash(self):
     """
     Make a hash
     :return: <str>
     """
     doc = self.json()
     block_str = json.dumps(doc, sort_keys=True, ensure_ascii=False)
     return _sha256.sha256(block_str.encode()).hexdigest()
Ejemplo n.º 28
0
def getPoolTxnData(poolId, newPoolTxnNodeNames):
    data = {}
    data["seeds"] = {}
    data["txns"] = []
    data['nodesWithBls'] = {}
    for index, n in enumerate(newPoolTxnNodeNames, start=1):
        newStewardAlias = poolId + "Steward" + str(index)
        stewardSeed = (newStewardAlias + "0" *
                       (32 - len(newStewardAlias))).encode()
        data["seeds"][newStewardAlias] = stewardSeed
        stewardSigner = SimpleSigner(seed=stewardSeed)
        data["txns"].append(
            Member.nym_txn(nym=stewardSigner.identifier,
                           verkey=stewardSigner.verkey,
                           role=STEWARD,
                           name=poolId + "Steward" + str(index),
                           seq_no=index,
                           txn_id=sha256("{}".format(
                               stewardSigner.verkey).encode()).hexdigest()))

        newNodeAlias = n
        nodeSeed = (newNodeAlias + "0" * (32 - len(newNodeAlias))).encode()
        data["seeds"][newNodeAlias] = nodeSeed
        nodeSigner = SimpleSigner(seed=nodeSeed)

        _, bls_key, key_proof = create_default_bls_crypto_factory(
        ).generate_bls_keys(seed=data['seeds'][n])
        data['nodesWithBls'][n] = True

        node_txn = Steward.node_txn(
            steward_nym=stewardSigner.verkey,
            node_name=newNodeAlias,
            nym=nodeSigner.verkey,
            ip="127.0.0.1",
            node_port=genHa()[1],
            client_port=genHa()[1],
            client_ip="127.0.0.1",
            blskey=bls_key,
            bls_key_proof=key_proof,
            services=[VALIDATOR],
            txn_id=sha256("{}".format(nodeSigner.verkey).encode()).hexdigest())

        data["txns"].append(node_txn)

    return data
Ejemplo n.º 29
0
def getPoolTxnData(poolId, newPoolTxnNodeNames):
    data = {}
    data["seeds"] = {}
    data["txns"] = []
    data['nodesWithBls'] = {}
    for index, n in enumerate(newPoolTxnNodeNames, start=1):
        newStewardAlias = poolId + "Steward" + str(index)
        stewardSeed = (newStewardAlias + "0" *
                       (32 - len(newStewardAlias))).encode()
        data["seeds"][newStewardAlias] = stewardSeed
        stewardSigner = SimpleSigner(seed=stewardSeed)
        data["txns"].append({
            TARGET_NYM: stewardSigner.verkey,
            ROLE: STEWARD, TXN_TYPE: NYM,
            ALIAS: poolId + "Steward" + str(index),
            TXN_ID: sha256("{}".format(stewardSigner.verkey).encode()).hexdigest()
        })

        newNodeAlias = n
        nodeSeed = (newNodeAlias + "0" * (32 - len(newNodeAlias))).encode()
        data["seeds"][newNodeAlias] = nodeSeed
        nodeSigner = SimpleSigner(seed=nodeSeed)
        node_txn = {
            TARGET_NYM: nodeSigner.verkey,
            TXN_TYPE: NODE,
            f.IDENTIFIER.nm: stewardSigner.verkey,
            DATA: {
                CLIENT_IP: "127.0.0.1",
                ALIAS: newNodeAlias,
                NODE_IP: "127.0.0.1",
                NODE_PORT: genHa()[1],
                CLIENT_PORT: genHa()[1],
                SERVICES: [VALIDATOR],
            },
            TXN_ID: sha256("{}".format(nodeSigner.verkey).encode()).hexdigest()
        }

        _, bls_key = create_default_bls_crypto_factory().generate_bls_keys(
            seed=data['seeds'][n])
        node_txn[DATA][BLS_KEY] = bls_key
        data['nodesWithBls'][n] = True

        data["txns"].append(node_txn)

    return data
Ejemplo n.º 30
0
def long_time_algorithm(data):
    result = run_algorithm(data)
    url = generate_table(agents=data['agents'],
                         items=data['items'],
                         data=result,
                         file_name=sha256(str(
                             data['values']).encode('utf-8')).hexdigest(),
                         data_json=data)
    send_email(data['email'], url)
Ejemplo n.º 31
0
def getPoolTxnData(poolId, newPoolTxnNodeNames):
    data = {}
    data["seeds"] = {}
    data["txns"] = []
    data['nodesWithBls'] = {}
    for index, n in enumerate(newPoolTxnNodeNames, start=1):
        newStewardAlias = poolId + "Steward" + str(index)
        stewardSeed = (newStewardAlias + "0" *
                       (32 - len(newStewardAlias))).encode()
        data["seeds"][newStewardAlias] = stewardSeed
        stewardSigner = SimpleSigner(seed=stewardSeed)
        data["txns"].append(
            Member.nym_txn(nym=stewardSigner.identifier,
                           verkey=stewardSigner.verkey,
                           role=STEWARD,
                           name=poolId + "Steward" + str(index),
                           seq_no=index,
                           txn_id=sha256("{}".format(stewardSigner.verkey).encode()).hexdigest()))

        newNodeAlias = n
        nodeSeed = (newNodeAlias + "0" * (32 - len(newNodeAlias))).encode()
        data["seeds"][newNodeAlias] = nodeSeed
        nodeSigner = SimpleSigner(seed=nodeSeed)

        _, bls_key = create_default_bls_crypto_factory().generate_bls_keys(
            seed=data['seeds'][n])
        data['nodesWithBls'][n] = True

        node_txn = Steward.node_txn(
            steward_nym=stewardSigner.verkey,
            node_name=newNodeAlias,
            nym=nodeSigner.verkey,
            ip="127.0.0.1",
            node_port=genHa()[1],
            client_port=genHa()[1],
            client_ip="127.0.0.1",
            blskey=bls_key,
            services=[VALIDATOR],
            txn_id=sha256("{}".format(nodeSigner.verkey).encode()).hexdigest()
        )

        data["txns"].append(node_txn)

    return data
Ejemplo n.º 32
0
 def serializeForSig(self, msg):
     if msg["operation"].get(TXN_TYPE) == ATTRIB:
         msgCopy = deepcopy(msg)
         keyName = {RAW, ENC, HASH
                    }.intersection(set(msgCopy["operation"].keys())).pop()
         msgCopy["operation"][keyName] = sha256(
             msgCopy["operation"][keyName].encode()).hexdigest()
         return super().serializeForSig(msgCopy)
     else:
         return super().serializeForSig(msg)
Ejemplo n.º 33
0
 def storeTxnInLedger(self, result):
     if result[TXN_TYPE] == ATTRIB:
         # Creating copy of result so that `RAW`, `ENC` or `HASH` can be
         # replaced by their hashes. We do not insert actual attribute data
         # in the ledger but only the hash of it.
         result = deepcopy(result)
         if RAW in result:
             result[RAW] = sha256(result[RAW].encode()).hexdigest()
         elif ENC in result:
             result[ENC] = sha256(result[ENC].encode()).hexdigest()
         elif HASH in result:
             result[HASH] = result[HASH]
         else:
             error("Transaction missing required field")
         merkleInfo = self.addToLedger(result)
     else:
         merkleInfo = self.addToLedger(result)
     result.update(merkleInfo)
     return result
Ejemplo n.º 34
0
def make_key(request: web.Request) -> str:
    key_parts: List[str] = [
        request.method,
        request.rel_url.path_qs,
        request.url.host,
        request.content_type,
    ]
    key = "#".join(part for part in key_parts)
    key = sha256(key.encode()).hexdigest()
    return key
Ejemplo n.º 35
0
def verify_sign(pubkey, message, signature):
    """
    验证签名
    :param pubkey:公钥
    :param message:内容
    :param signature:签名
    :return:
    """
    verifier = VerifyingKey.from_pem(pubkey)
    h = sha256(str(message).encode('utf-8'))
    return verifier.verify(binascii.unhexlify(signature), h.digest())
Ejemplo n.º 36
0
    def shasum(self) -> str:
        stdout.print('Calculating checksum of {}'.format(self.file))
        response = request.urlopen(self._mirror + self.file)
        length = int(response.headers.get('content-length'))
        checksum = sha256()
        count = 0
        for chunk in iter(lambda: response.read(CHUNK_SIZE), b''):
            checksum.update(chunk)
            count += len(chunk)
            stdout.progress(count, length)

        return checksum.hexdigest()
Ejemplo n.º 37
0
    def getEncodedAttrs(cls, attrs):
        """
        This function will encode all the attributes to 256 bit integers

        :param attrs: The attributes to pass in credentials
        :return:
        """

        return {
            key:
            cmod.Conversion.bytes2integer(sha256(value.encode()).digest())
            for key, value in attrs.items()
        }
Ejemplo n.º 38
0
def register_new(args):
    # look up the correct way to do this
    if args['password1'] == args['password2']:
        user = User()
        user.username = args['username']
        user.password = sha256(args['password1']).hexdigest()
        try:
            if db_add(user):
                flash('Account created. Please login.', 'success')
                return index()
        except IntegrityError as e:
            flash('Username already taken.', 'error')
    else:
        flash('Passwords do not match', 'error')
    return registration()
Ejemplo n.º 39
0
def test_sha256_sanity():
    x = _sha256.sha256()
    AreEqual(x.block_size, 64)
    AreEqual(x.digest(),
             "\xe3\xb0\xc4B\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99o\xb9$'\xaeA\xe4d\x9b\x93L\xa4\x95\x99\x1bxR\xb8U")
    AreEqual(x.digest_size, 32)
    AreEqual(x.digest_size, x.digestsize)
    AreEqual(x.hexdigest(),
             'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
    AreEqual(x.name, "SHA256")
    x.update("abc")
    AreEqual(x.hexdigest(),
             'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')
    
    x_copy = x.copy()
    Assert(x!=x_copy)
    AreEqual(x.hexdigest(), x_copy.hexdigest())
Ejemplo n.º 40
0
 def wrapper(*args, **kwargs):
     session = request.environ.get('beaker.session')
     if request.method == 'POST':
         csrf = request.POST.get('csrf')
         if not csrf or csrf != session.get(token_id):
             msg = 'Dados inválidos ou expirados, recaregue a página.'
             if json_response:
                 return dict(status=False, info=msg)
             else:
                 abort(403, msg)
     elif request.method == 'GET':
         csrf = sha256(os.urandom(8)).hexdigest()
         session[token_id] = csrf
     else:
         csrf = None
     # callback function with csrf argument injected
     kwargs.update({'csrf': csrf})
     return func(*args, **kwargs)
Ejemplo n.º 41
0
 def put_into_seq_no_db(txn):
     # If there is no reqId, then it's genesis txn
     if get_req_id(txn) is None:
         return
     txn_new = copy.deepcopy(txn)
     operation = get_payload_data(txn_new)
     operation[TXN_TYPE] = get_type(txn_new)
     dct = {
         f.IDENTIFIER.nm: get_from(txn_new),
         f.REQ_ID.nm: get_req_id(txn_new),
         OPERATION: operation,
     }
     if get_protocol_version(txn_new) is not None:
         dct[f.PROTOCOL_VERSION.nm] = get_protocol_version(txn_new)
     digest = sha256(serialize_msg_for_signing(dct)).hexdigest()
     seq_no = get_seq_no(txn_new)
     ledger_id = get_ledger_id_by_txn_type(operation[TXN_TYPE])
     line_to_record = str(ledger_id) + ReqIdrToTxn.delimiter + str(seq_no)
     dest_seq_no_db_storage.put(digest, line_to_record)
     return digest
Ejemplo n.º 42
0
 def _getDigest(req: Request):
     return sha256(req.identifier.encode())
Ejemplo n.º 43
0
from _sha256 import sha256
import wsgiref.handlers
import webapp2

import base
import browse
import handlers.async
from admin import post, model
from admin import usr
from admin import siteconf
from admin import comments
import rss
import sitemap

user = model.User.get_by_name("abillist")
user.passwd = sha256('abillistpwd').hexdigest()
user.admin = True
user.session_key = sha256(user.name + user.passwd).hexdigest()
user.save()

if __name__ == '__main__':
    application = webapp2.WSGIApplication([
        ('/', browse.Index),
        ('/json/loadcomments', handlers.async.CommentsLoader),
        ('/json/leavecomment', handlers.async.CommentRecv),
        ('/c/newpost', post.NewPost),
        ('/c/preview', post.Preview),
        ('/c/add', post.Add),
        ('/c/posts', post.List),
        ('/c/edit', post.Edit),
        ('/c/comments', comments.List),
Ejemplo n.º 44
0
    def bootstrapTestNodesCore(baseDir,
                           poolTransactionsFile,
                           domainTransactionsFile,
                           domainTxnFieldOrder,
                           ips, nodeCount, clientCount,
                           nodeNum, startingPort):
        if not ips:
            ips = ['127.0.0.1'] * nodeCount
        else:
            ips = ips.split(",")
            if len(ips) != nodeCount:
                if len(ips) > nodeCount:
                    ips = ips[:nodeCount]
                else:
                    ips = ips + ['127.0.0.1'] * (nodeCount - len(ips))

        poolLedger = Ledger(CompactMerkleTree(),
                            dataDir=baseDir,
                            fileName=poolTransactionsFile)
        poolLedger.reset()

        domainLedger = Ledger(CompactMerkleTree(),
                              serializer=CompactSerializer(fields=
                                                           domainTxnFieldOrder),
                              dataDir=baseDir,
                              fileName=domainTransactionsFile)
        domainLedger.reset()

        steward1Nym = None
        for num in range(1, nodeCount + 1):
            stewardName = "Steward" + str(num)
            sigseed = TestNetworkSetup.getSigningSeed(stewardName)
            verkey = Signer(sigseed).verhex
            stewardNym = TestNetworkSetup.getNymFromVerkey(verkey)
            txn = {
                TARGET_NYM: stewardNym,
                TXN_TYPE: NYM,
                ROLE: STEWARD,
                ALIAS: stewardName,
                TXN_ID: sha256(stewardName.encode()).hexdigest()
            }
            if num == 1:
                steward1Nym = stewardNym
            else:
                # The first steward adds every steward
                txn[f.IDENTIFIER.nm] = steward1Nym
            domainLedger.add(txn)

            nodeName = "Node" + str(num)
            nodePort, clientPort = startingPort + (num * 2 - 1), startingPort \
                                   + (num * 2)
            ip = ips[num - 1]
            sigseed = TestNetworkSetup.getSigningSeed(nodeName)
            if nodeNum == num:
                _, verkey = initLocalKeep(nodeName, baseDir, sigseed, True)
                verkey = verkey.encode()
                print("This node with name {} will use ports {} and {} for "
                      "nodestack and clientstack respectively"
                      .format(nodeName, nodePort, clientPort))
            else:
                verkey = Signer(sigseed).verhex
            txn = {
                TARGET_NYM: TestNetworkSetup.getNymFromVerkey(verkey),
                TXN_TYPE: NEW_NODE,
                f.IDENTIFIER.nm: stewardNym,
                DATA: {
                    CLIENT_IP: ip,
                    ALIAS: nodeName,
                    CLIENT_PORT: clientPort,
                    NODE_IP: ip,
                    NODE_PORT: nodePort
                },
                TXN_ID: sha256(nodeName.encode()).hexdigest()
            }
            poolLedger.add(txn)

        for num in range(1, clientCount + 1):
            clientName = "Client" + str(num)
            sigseed = TestNetworkSetup.getSigningSeed(clientName)
            verkey = Signer(sigseed).verhex
            txn = {
                f.IDENTIFIER.nm: steward1Nym,
                TARGET_NYM: TestNetworkSetup.getNymFromVerkey(verkey),
                TXN_TYPE: NYM,
                ALIAS: clientName,
                TXN_ID: sha256(clientName.encode()).hexdigest()
            }
            domainLedger.add(txn)

        poolLedger.stop()
        domainLedger.stop()
Ejemplo n.º 45
0
import _hashlib

from ._util import PY2, PY33


if PY2:
    import _md5
    import _sha
    import _sha256
    import _sha512


    md5 = type(_md5.new())
    sha1 = type(_sha.new())
    sha224 = type(_sha256.sha224())
    sha256 = type(_sha256.sha256())
    sha384 = type(_sha512.sha384())
    sha512 = type(_sha512.sha512())
elif PY33:
    import _md5
    import _sha1
    import _sha256
    import _sha512


    md5 = type(_md5.md5())
    sha1 = type(_sha1.sha1())
    sha224 = type(_sha256.sha224())
    sha256 = type(_sha256.sha256())
    sha384 = type(_sha512.sha384())
    sha512 = type(_sha512.sha512())