Ejemplo n.º 1
0
    def sign_der(pri_key_string, raw_data, password=None):
        """

        signature data with private key string

        Args:
            pri_key_string:base64 private key string
            raw_data: string data
            password:

        Returns:base64 encoded signature string

        """
        try:
            password = examine_password(password)
            pri_key_string_bytes = Encoder.str_to_base64_byte(pri_key_string)
            loaded_private_key = serialization.load_der_private_key(
                pri_key_string_bytes,
                password=password,
                backend=default_backend())
            signature_string = loaded_private_key.sign(
                raw_data.encode(encoding="utf-8"), ec.ECDSA(hashes.SHA256()))
            return Encoder.bytes_to_base64_str(signature_string)
        except Exception:
            logger.exception("signature error")
            return None
Ejemplo n.º 2
0
    def generate_der_keys(password=None):
        """
        generate private ,public key string tuple
        Args:
            password:

        Returns:
            private ,public key string tuple

        """
        password = examine_password(password)
        private_key = ec.generate_private_key(ec.SECP256K1(),
                                              default_backend())

        serialized_private = private_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.BestAvailableEncryption(
                password))

        pri_key_string = Encoder.bytes_to_base64_str(serialized_private)
        logger.debug("pri_key_string:%s" % pri_key_string)
        puk = private_key.public_key()
        serialized_public = puk.public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo)
        pub_key_string = Encoder.bytes_to_base64_str(serialized_public)
        logger.debug("pub_key_string:%s" % pub_key_string)
        return pri_key_string, pub_key_string
Ejemplo n.º 3
0
 def login(self, username=None):
     header = {'Content-Type': 'application/json'}
     data = {'public_key': self.public_key, 'username': username}
     resp = yield treq.post(url=self.url + 'account/v1/login/',
                            headers=header,
                            json=data,
                            persistent=False)
     confirm_info = yield treq.json_content(resp)
     logger.debug("login response: %s", confirm_info)
     self.nonce = confirm_info['message']
     logger.debug('nonce: %s', self.nonce)
     signature = ECCipher.create_signature(self.account.private_key,
                                           self.nonce)
     header_confirm = {'Content-Type': 'application/json'}
     data_confirm = {
         'public_key': self.public_key,
         'code': Encoder.bytes_to_hex(signature)
     }
     resp = yield treq.post(self.url + 'account/v1/confirm/',
                            headers=header_confirm,
                            json=data_confirm,
                            persistent=False)
     confirm_info = yield treq.json_content(resp)
     self.token = confirm_info['message']
     return confirm_info['status']
Ejemplo n.º 4
0
 def verify_signature(pub_key_string, signature, raw_data):
     try:
         loaded_public_key = serialization.load_pem_public_key(
             pub_key_string, backend=default_backend())
         loaded_public_key.verify(Encoder.str_to_base64_byte(signature),
                                  raw_data, ec.ECDSA(hashes.SHA256()))
         return True
     except Exception:
         logger.exception("verify signature error")
         return False
Ejemplo n.º 5
0
 def get_all_orders(self):
     num = self.contract.call().numOrders()
     data = dict()
     for i in range(num):
         order = self.contract.call().orderRecords(i + 1)
         market_hash = Encoder.bytes_to_base64_str(order[0])
         rsa = Encoder.bytes_to_base64_str(order[1])[:10] + "..."
         status = order[10]
         item = data.get(market_hash, [])
         seller_addr = order[3]
         buyer_addr = order[2]
         item.append({
             'public_key': rsa,
             'status': status,
             'order_id': i + 1,
             'seller_addr': seller_addr,
             'buyer_addr': buyer_addr
         })
         data[market_hash] = item
     return data
Ejemplo n.º 6
0
 def sign(pri_key_string, raw_data, password=None):
     try:
         password = examine_password(password)
         loaded_private_key = serialization.load_pem_private_key(
             pri_key_string, password=password, backend=default_backend())
         signature_string = loaded_private_key.sign(
             raw_data, ec.ECDSA(hashes.SHA256()))
         return Encoder.bytes_to_base64_str(signature_string)
     except Exception:
         logger.exception("pem sign error")
         return None
Ejemplo n.º 7
0
 def publish_product(self,
                     selected_id,
                     title,
                     ptype,
                     description,
                     price,
                     tags,
                     start_date,
                     end_date,
                     category=None,
                     cover_image=None):
     logger.debug("start publish product")
     header = {'Content-Type': 'multipart/form-data'}  # 'application/json'}
     header['MARKET-KEY'] = self.public_key
     header['MARKET-TOKEN'] = self.token
     logger.debug('header token: %s', self.token)
     data = {
         'owner_address': self.public_key,
         'title': title,
         'ptype': ptype,
         'description': description,
         'price': price,
         'tags': tags,
         'start_date': start_date,
         'end_date': end_date,
         'category': category
     }
     signature_source = str(
         self.public_key) + str(title) + str(ptype) + str(
             description) + str(price) + MarketClient.str_to_timestamp(
                 start_date) + MarketClient.str_to_timestamp(end_date)
     signature = ECCipher.create_signature(self.account.private_key,
                                           signature_source)
     data['signature'] = Encoder.bytes_to_hex(signature)
     logger.debug("signature: %s", data['signature'])
     try:
         url = self.url + 'product/v1/allproducts/'
         resp = yield treq.post(
             url,
             files=dict(cover_image=open(cover_image, 'rb')),
             headers=header,
             data=data,
             persistent=False)
         confirm_info = yield treq.json_content(resp)
         logger.debug('market_hash: %s',
                      confirm_info['data']['market_hash'])
         market_hash = confirm_info['data']['market_hash']
     except Exception as e:
         logger.exception(e)
     if ptype == 'file' or ptype == 'stream':
         publish_file_update(market_hash, selected_id)
     return market_hash
Ejemplo n.º 8
0
    def get_public_key_from_private_key(pri_key_string, password=None):
        """
        get public key from private key string

        Args:
            pri_key_string: private key string
            password: read default value from config file

        Returns:
            base64(public key)
        """

        password = examine_password(password)
        pri_key_string_bytes = Encoder.str_to_base64_byte(pri_key_string)

        loaded_private_key = serialization.load_der_private_key(
            pri_key_string_bytes, password=password, backend=default_backend())
        puk = loaded_private_key.public_key()
        serialized_public = puk.public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo)
        return Encoder.bytes_to_base64_str(serialized_public)
Ejemplo n.º 9
0
    def __generate_nonce_signature_and_get_token(self, header, nonce, pub_key_str, pri_key):
        url = '%s/account/v1/confirm/' % HOST
        print("nonce:%s" % nonce)
        nonce_signature = ECCipher.create_signature(pri_key, nonce)

        payload = {"public_key": pub_key_str, "code": Encoder.bytes_to_hex(nonce_signature)}
        confirm_resp = requests.post(url, headers=header, json=payload)
        print("response:%s" , confirm_resp.text)
        self.assertEqual(confirm_resp.status_code, 200)
        parsed_json = json.loads(confirm_resp.text)
        self.assertEqual(parsed_json['status'], 1)
        token = parsed_json['message']
        print("token:%s" % token)
        return token
Ejemplo n.º 10
0
def test_server_chain():
    os.chdir(root_dir)
    server_web3 = chain.default_web3
    # chain.utils.deploy_contract(config.chain.core_contract)
    buyertrans = BuyerAgent(server_web3, config.chain.core_contract)
    print(server_web3.eth.defaultAccount)
    # desc_hash_base64 = 'AQkKqDxtNIRJ+1V82J5lP2/fRj/zbJ+2n0GzUF52Wsc='
    # desc_hash = Encoder.str_to_base64_byte(desc_hash_base64)
    # public_key = RSACipher.load_public_key()
    # print('pubkey ' + str(len(public_key)))
    # order_info = OrderInfo(
    #     desc_hash=desc_hash,
    #     buyer_rsa_pubkey=public_key,
    #     seller=buyertrans.web3.eth.defaultAccount,
    #     proxy=buyertrans.web3.eth.defaultAccount,
    #     secondary_proxy=buyertrans.web3.eth.defaultAccount,
    #     proxy_value=10,
    #     value=20,
    #     time_allowed=100
    # )
    # test_server_id = buyertrans.place_order(order_info)
    # print(test_server_id)
    # buyertrans.withdraw_order(test_server_id)
    # print(buyertrans.query_order(test_server_id))
    order_num = buyertrans.get_order_num()
    print(order_num)
    latest_order_info = buyertrans.query_order(order_num - 1)
    private_key_file_path = join_with_root(config.wallet.private_key_file)
    password_path = join_with_root(config.wallet.private_key_password_file)
    with open(password_path) as f:
        password = f.read()
    priv_key, pub_key = ECCipher.load_key_pair_from_private_key(
        private_key_file_path, password)
    pub_key_bytes = Encoder.str_to_base64_byte(pub_key)
    pub_key_loaded = load_der_public_key(pub_key_bytes,
                                         backend=default_backend())
    # print(Encoder.str_to_base64_byte(pub_key))
    # print(len(Encoder.str_to_base64_byte(pub_key)))
    # print(pub_key_bytes_to_addr(Encoder.str_to_base64_byte(pub_key)))
    # print(len(pub_key_bytes_to_addr(Encoder.str_to_base64_byte(pub_key))))
    print(get_addr_from_public_key(pub_key_loaded))
    print(to_bytes(hexstr=latest_order_info[2]))
    print(len(to_bytes(hexstr=latest_order_info[2])))
Ejemplo n.º 11
0
    def verify_sign(public_key, signature, message):
        """
        verify signature
        Args:
            public_key:public key object
            signature:signature string
            raw_data:data string

        Returns:
            True: is valid signature;False: is invalid signature

        """
        if isinstance(message, str):
            message = message.encode(encoding="utf-8")
        if isinstance(signature, str):
            signature = Encoder.hex_to_bytes(signature)
        try:
            public_key.verify(signature, message, ec.ECDSA(hashes.SHA256()))
        except Exception:
            logger.exception("verify signature error")
            return False
        else:
            return True
Ejemplo n.º 12
0
    def __generate_nonce_signature_and_get_token(self, header, nonce,
                                                 pub_key_str, pri_key):
        url = reverse('confirm')
        print("nonce:%s" % nonce)
        nonce_signature = ECCipher.create_signature(pri_key, nonce)

        payload = {
            "public_key": pub_key_str,
            "code": Encoder.bytes_to_hex(nonce_signature)
        }
        # self.client.head(header)
        confirm_resp = self.client.post(url,
                                        data=payload,
                                        format='json',
                                        **header)

        self.assertEqual(confirm_resp.status_code, 200)
        resp = confirm_resp.content.decode("utf-8")
        print("response:%s" % resp)
        parsed_json = json.loads(resp)
        self.assertEqual(parsed_json['status'], 1)
        token = parsed_json['message']
        print("token:%s" % token)
        return token
Ejemplo n.º 13
0
    def publish_product(self, selected_id, title, description, price, tags, start_date, end_date,
                        file_md5, size):

        logger.debug("start publish product")
        header = {'Content-Type': 'application/json'}
        header['MARKET-KEY'] = self.public_key
        header['MARKET-TOKEN'] = self.token
        logger.debug('header token: %s', self.token)
        data = {'owner_address': self.public_key, 'title': title, 'description': description,
                'price': price, 'tags': tags, 'start_date': start_date, 'end_date': end_date,
                'file_md5': file_md5, 'size': size}
        signature_source = str(self.public_key) + str(title) + str(description) + str(
            price) + MarketClient.str_to_timestamp(start_date) + MarketClient.str_to_timestamp(end_date) + str(file_md5)
        signature = ECCipher.create_signature(self.account.private_key, signature_source)
        data['signature'] = Encoder.bytes_to_hex(signature)
        logger.debug("signature: %s", data['signature'])
        resp = yield treq.post(self.url + 'product/v1/product/publish/', headers=header, json=data, persistent=False)
        confirm_info = yield treq.json_content(resp)
        print(confirm_info)

        logger.debug('market_hash: %s', confirm_info['data']['market_hash'])
        market_hash = confirm_info['data']['market_hash']
        publish_file_update(market_hash, selected_id)
        return market_hash
Ejemplo n.º 14
0
def is_valid_signature(public_key_string, raw_data, signature):
    public_key_bytes = Encoder.hex_to_bytes(public_key_string)
    public_key = ECCipher.create_public_key(public_key_bytes)
    logger.debug("is_valid_verify_code public_key:" + public_key_string +
                 ",raw_data:" + raw_data + ",signature:" + signature)
    return verify_signature(public_key, signature, raw_data)
Ejemplo n.º 15
0
def get_public_key(public_key_string):
    pub_key_bytes = Encoder.hex_to_bytes(public_key_string)
    return ECCipher.create_public_key(pub_key_bytes)
Ejemplo n.º 16
0
 def test_str_to_base64_byte(self):
     bs = Encoder.str_to_base64_byte(self.string)
     self.assertEqual(self.b, bs)
Ejemplo n.º 17
0
 def test_bytes_to_base64_str(self):
     self.assertEqual(Encoder.bytes_to_base64_str(self.b), self.string)