Exemplo n.º 1
0
def build_channel_request(client, channel_tx, channel_name):
    """
    Args:
        client: the client instance
        channel_tx: channel config file
        channel_name: channel name
    return channel request to create a channel
    """

    signatures = []
    prop_req = TXProposalRequest()
    with open(channel_tx, 'rb') as f:
        envelope = f.read()
        config = utils.extract_channel_config(envelope)

    orderer_config = E2E_CONFIG['test-network']['orderer']
    with open(orderer_config['tls_cacerts'], 'rb') as tls_cacerts:
        pem = tls_cacerts.read()

    opts = (('grpc.ssl_target_name_override', 'orderer.example.com'), )
    orderer = Orderer(endpoint=orderer_config['grpc_endpoint'],
                      pem=pem,
                      opts=opts)
    orderer_admin = get_orderer_org_admin(client)
    orderer_tx_context = TXContext(orderer_admin, Ecies(), prop_req, {})
    client.tx_context = orderer_tx_context
    orderer_admin_signature = client.sign_channel_config(config)
    orderer_admin_signature_bytes = orderer_admin_signature.SerializeToString()
    signatures.append(orderer_admin_signature_bytes)
    tx_id = orderer_tx_context.tx_id
    nonce = orderer_tx_context.nonce

    org1_admin = get_peer_org_admin(client, 'org1.example.com')
    org1_tx_context = TXContext(org1_admin, Ecies(), prop_req, {})
    client.tx_context = org1_tx_context
    org1_admin_signature = client.sign_channel_config(config)
    org1_admin_signature_bytes = org1_admin_signature.SerializeToString()

    signatures.append(org1_admin_signature_bytes)

    org2_admin = get_peer_org_admin(client, 'org2.example.com')
    org2_tx_context = TXContext(org2_admin, Ecies(), prop_req, {})
    client.tx_context = org2_tx_context
    org2_admin_signature = client.sign_channel_config(config)
    org2_admin_signature_bytes = org2_admin_signature.SerializeToString()
    signatures.append(org2_admin_signature_bytes)

    request = {
        'config': config,
        'signatures': signatures,
        'channel_name': channel_name,
        'orderer': orderer,
        'tx_id': tx_id,
        'nonce': nonce
    }

    return request
Exemplo n.º 2
0
    def test_string_to_signature(self):
        with open(self.channel_tx, 'rb') as f:
            channel_tx = f.read()

        channel_config = utils.extract_channel_config(channel_tx)

        client = Client()
        client.state_store = FileKeyValueStore(self.kv_store_path)

        orderer_org_admin = get_orderer_org_admin(client)
        orderer_org_admin_tx_context = \
            TXContext(orderer_org_admin, Ecies(), {})
        client.tx_context = orderer_org_admin_tx_context

        orderer_org_admin_signature = client.sign_channel_config(
            channel_config)
        orderer_org_admin_signature_bytes = \
            orderer_org_admin_signature.SerializeToString()

        proto_signature = utils.string_to_signature(
            [orderer_org_admin_signature_bytes])

        self.assertIsInstance(proto_signature, list)
        self.assertTrue(
            'OrdererMSP' in proto_signature[0].signature_header.__str__())
Exemplo n.º 3
0
def ecdsa_verify(message, signature, key_data):
    """
	:param message: character string to sign 
	:param signature: mac value in the return message 
	:param pub_key_file: gateway public key path
	:return: return True or False
	"""
    # read the content of public key
    # path = os.path.abspath('.')
    # file = os.path.join(path, pub_key_file)
    # print('gateway public key directory path: ', file)
    # pub_key_file = open(file, "rb")
    # key_data = pub_key_file.read()
    # pub_key_file.close()

    # load X509 cert public key
    cert = load_pem_x509_certificate(key_data, default_backend())
    # print("public key cert:", cert)

    # read the content of public key
    public_key = cert.public_key()
    # print("the content of public key public_key:", public_key)

    # read the signed data
    mac = signature

    # verify the signature
    verify_results = Ecies().verify(public_key=public_key,
                                    message=message.encode('utf-8'),
                                    signature=base64.b64decode(mac))
    # print("verify_results:", verify_results)

    # return value T or F
    return verify_results
Exemplo n.º 4
0
def ecdsa_sign(message, key_data):
    """
	:param message: character string to sign
	:param pri_key_file_name: user private key path
	:return: return signature value in base64 format
	"""
    # Read the pri_key_file
    # path = os.path.abspath('.')
    # file = os.path.join(path, pri_key_file_name)
    # print('private key storage path: ', file)
    # pri_key_file = open(file, "rb")
    # key_data = pri_key_file.read()
    # pri_key_file.close()

    # load private key
    skey = load_pem_private_key(key_data,
                                password=None,
                                backend=default_backend())

    # sign using the function in the official library
    signature = Ecies(CURVE_P_256_Size, SHA2).sign(private_key=skey,
                                                   message=message)

    # print("signature:", signature)
    # return signature value in base64 format base64.b64encode(signature)
    return signature
Exemplo n.º 5
0
def ecdsa_verify(message, signature, pub_key_file):
    """
	:param message: 待签名字符串
	:param signature: 返回报文中的 mac值
	:param pub_key_file: 网关公钥路径
	:return: 返回 True or False
	"""
    # 读取公钥内容
    path = os.path.abspath('.')
    file = os.path.join(path, pub_key_file)
    pub_key_file = open(file, "rb")
    key_data = pub_key_file.read()
    pub_key_file.close()

    # 加载X509证书 公钥证书
    cert = load_pem_x509_certificate(key_data, default_backend())
    # print("公钥证书cert:", cert)

    # 取出公钥秘钥内容
    public_key = cert.public_key()
    # print("公钥秘钥内容public_key:", public_key)

    # 读取签名后的数据
    mac = signature

    # 验签
    verify_results = Ecies().verify(public_key=public_key,
                                    message=message.encode('utf-8'),
                                    signature=base64.b64decode(mac))
    # print("verify_results:", verify_results)

    # 返回值为 T or F
    return verify_results
Exemplo n.º 6
0
    def test_build_header(self):
        timestamp = utils.current_timestamp()

        client = Client()
        client.state_store = FileKeyValueStore(self.kv_store_path)

        orderer_org_admin = get_orderer_org_admin(client)
        orderer_org_admin_tx_context = \
            TXContext(orderer_org_admin, Ecies(), {})
        client.tx_context = orderer_org_admin_tx_context

        orderer_org_admin_serialized = utils.create_serialized_identity(
            orderer_org_admin)
        serialized_identity = identities_pb2.SerializedIdentity()
        serialized_identity.ParseFromString(orderer_org_admin_serialized)

        proto_channel_header = utils.build_channel_header(
            common_pb2.HeaderType.Value('CONFIG_UPDATE'),
            orderer_org_admin_tx_context.tx_id,
            self.channel_id,
            timestamp
        )

        channel_header = utils.build_header(
            orderer_org_admin_tx_context.identity,
            proto_channel_header,
            orderer_org_admin_tx_context.nonce
        )
        self.assertIsInstance(channel_header, common_pb2.Header)
Exemplo n.º 7
0
    def channel_create(self, orderer_name, channel_name, requestor,
                       config_yaml, channel_profile):
        """
        Create a channel, send request to orderer, and check the response

        :param orderer_name: Name of orderer to send request to
        :param channel_name: Name of channel to create
        :param requestor: Name of creator
        :param config_yaml: Directory path of config yaml to be set for FABRIC_
        CFG_PATH variable
        :param channel_profile: Name of the channel profile defined inside
        config yaml file
        :return: True (creation succeeds) or False (creation failed)
        """
        if self.get_channel(channel_name):
            _logger.warning("channel {} already existed when creating".format(
                channel_name))
            return False

        orderer = self.get_orderer(orderer_name)
        if not orderer:
            _logger.error("No orderer_name instance found with name {}".format(
                orderer_name))
            return False

        tx = self.generate_channel_tx(channel_name, config_yaml,
                                      channel_profile)
        if tx is None:
            _logger.error('Configtx is empty')
            return False
        _logger.info("Configtx file successfully created in current directory")

        with open(tx, 'rb') as f:
            envelope = f.read()
            config = utils.extract_channel_config(envelope)

        # convert envelope to config
        self.tx_context = TXContext(requestor, Ecies(), {})
        tx_id = self.tx_context.tx_id
        nonce = self.tx_context.nonce
        signatures = []
        org1_admin_signature = self.sign_channel_config(config)
        # append org1_admin_signature to signatures
        signatures.append(org1_admin_signature)

        request = {
            'tx_id': tx_id,
            'nonce': nonce,
            'signatures': signatures,
            'config': config,
            'orderer': orderer,
            'channel_name': channel_name
        }
        response = self._create_channel(request)

        if response[0].status == 200:
            self.new_channel(channel_name)
            return True
        else:
            return False
Exemplo n.º 8
0
 def sign(self, message):
     log_info("ECDSA sign")
     # load private key
     # Sign using the function in the official library
     signature = Ecies(CURVE_P_256_Size,
                       SHA2).sign(private_key=self.private_key_data,
                                  message=message.encode('utf-8'))
     # print("signature:", signature)
     # return signarure value in base64 format
     return base64.b64encode(signature)
Exemplo n.º 9
0
    def channel_create(self, orderer_name, channel_name, requester, tx):
        """
        Create a channel, send request to orderer, and check the response

        :param orderer_name: Name of orderer to send request to
        :param channel_name: Name of channel to create
        :param requester: Name of creator
        :param tx: Path to the new channel tx file
        :return: True (creation succeeds) or False (creation failed)
        """
        if self.get_channel(channel_name):
            logging.warning("channel {} already existed when creating".format(
                channel_name))
            return True

        orderer = self.get_orderer(orderer_name)
        if not orderer:
            logging.error("No orderer_name instance found with name {}".format(
                orderer_name))
            return False

        with open(tx, 'rb') as f:
            envelope = f.read()
            config = extract_channel_config(envelope)

        # convert envelope to config
        self.tx_context = TXContext(requester, Ecies(), {})
        tx_id = self.tx_context.tx_id
        nonce = self.tx_context.nonce
        signatures = []
        org1_admin_signature = self.sign_channel_config(config)
        # append org1_admin_signature to signatures
        signatures.append(org1_admin_signature)

        request = {
            'tx_id': tx_id,
            'nonce': nonce,
            'signatures': signatures,
            'config': config,
            'orderer': orderer,
            'channel_name': channel_name
        }
        q = Queue(1)
        response = self._create_channel(request)
        response.subscribe(on_next=lambda x: q.put(x),
                           on_error=lambda x: q.put(x))

        status, _ = q.get(timeout=5)
        if status.status == 200:
                self.new_channel(channel_name)
                return True
        else:
            return False
Exemplo n.º 10
0
    def verify(self, message, signature):
        log_info("ECDSA verify signature")
        print(message)
        # read the signed data
        mac = signature
        # verify the signature
        verify_results = Ecies().verify(public_key=self.pubilc_key_data,
                                        message=message.encode('utf-8'),
                                        signature=base64.b64decode(mac))
        # print("verify_results:", verify_results)

        # return value T or F
        return verify_results
Exemplo n.º 11
0
    def test_string_to_signature(self):
        with open(self.channel_tx, 'rb') as f:
            channel_tx = f.read()

        channel_config = utils.extract_channel_config(channel_tx)

        client = Client('test/fixtures/network.json')

        orderer_org_admin = get_orderer_org_user(
            state_store=client.state_store)
        orderer_org_admin_tx_context = \
            TXContext(orderer_org_admin, Ecies(), {})
        client.tx_context = orderer_org_admin_tx_context

        orderer_org_admin_signature = client.sign_channel_config(
            channel_config)

        proto_signature = utils.string_to_signature(
            [orderer_org_admin_signature])

        self.assertIsInstance(proto_signature, list)
        self.assertTrue(
            'OrdererMSP' in proto_signature[0].signature_header.__str__())
Exemplo n.º 12
0
def ecdsa_sign(message, key_data):
    """
	:param message: 待签名字符串
	:param pri_key_file_name: 用户私钥路径
	:return: 返回base64编码格式的签名值
	"""
    # Read the pri_key_file
    # path = os.path.abspath('.')
    # file = os.path.join(path, pri_key_file_name)
    # print('私钥目录路径: ', file)
    # pri_key_file = open(file, "rb")
    # key_data = pri_key_file.read()
    # pri_key_file.close()

    # 加载私钥
    skey = load_pem_private_key(key_data, password=None, backend=default_backend())

    # 使用官方库中的方法签名
    signature = Ecies(CURVE_P_256_Size, SHA2).sign(private_key=skey, message=message)

    # print("signature:", signature)
    # 返回base64编码格式的签名值 base64.b64encode(signature)
    return signature
Exemplo n.º 13
0
    def create_channel(self, orderer_name, channel, creator, tx):
        """
        Create a channel
        :param orderer_name: Name of orderer to send request to
        :param channel: Name of channel to create
        :param creator: Name of creator
        :param tx: Path to the new channel tx file
        :return:
        """
        orderer = self.get_orderer(orderer_name)
        if not orderer:
            logging.error("No orderer_name instance found with name {}".format(
                orderer_name))
            return None

        with open(tx, 'rb') as f:
            envelope = f.read()
            config = extract_channel_config(envelope)

        # convert envelope to config
        self.tx_context = TXContext(creator, Ecies(), {})
        tx_id = self.tx_context.tx_id
        nonce = self.tx_context.nonce
        signatures = []
        org1_admin_signature = self.sign_channel_config(config)
        # append org1_admin_signature to signatures
        signatures.append(org1_admin_signature)

        request = {
            'tx_id': tx_id,
            'nonce': nonce,
            'signatures': signatures,
            'config': config,
            'orderer': orderer,
            'channel_name': channel
        }
        return self._create_channel(request)
Exemplo n.º 14
0
def ecdsa_sign(message, pri_key_file_name):
    """
	:param message: 待签名字符串
	:param pri_key_file_name: 用户私钥路径
	:return: 返回base64编码格式的签名值
	"""
    # Read the pri_key_file
    path = os.path.abspath('.')
    file = os.path.join(path, pri_key_file_name)
    pri_key_file = open(file, "rb")
    key_data = pri_key_file.read()
    pri_key_file.close()

    # 加载私钥
    skey = load_pem_private_key(key_data,
                                password=None,
                                backend=default_backend())

    # 使用官方库中的方法签名
    signature = Ecies().sign(private_key=skey, message=message.encode('utf-8'))

    # print("signature:", signature)
    # 返回base64编码格式的签名值
    return base64.b64encode(signature)
Exemplo n.º 15
0
    def test_create_channel_missing_signatures(self):
        signatures = []

        with open(self.orderer_tls_certs) as f:
            pem = f.read()

        opts = (('grpc.ssl_target_name_override', 'orderer.example.com'), )
        orderer = Orderer(pem=pem, opts=opts)

        with open(self.configtx_path, 'rb') as f:
            envelope = f.read()

        # convert envelope to config
        config = extract_channel_config(envelope)

        channel_name = 'businesschannel'

        # signatures orderer admin
        orderer_admin = get_orderer_org_admin(self.client)
        orderer_admin_tx_context = TXContext(orderer_admin, Ecies(), {})
        self.client.tx_context = orderer_admin_tx_context

        orderer_admin_signature = self.client.sign_channel_config(config)
        orderer_admin_signature.SerializeToString()

        # take the tx_id and nonce from the oderer user context
        tx_id = orderer_admin_tx_context.tx_id
        nonce = orderer_admin_tx_context.nonce

        # reset the state store to handle different
        # users with one client object
        self.client.state_store = FileKeyValueStore(self.kv_store_path)

        # signatures org1 admin
        org1_admin = get_peer_org_user(self.client, 'org1.example.com')
        org1_admin_tx_context = TXContext(org1_admin, Ecies(), {})
        self.client.tx_context = org1_admin_tx_context

        org1_admin_signature = self.client.sign_channel_config(config)
        org1_admin_signature.SerializeToString()

        # reset the state store to handle different
        # users with one client object
        self.client.state_store = FileKeyValueStore(self.kv_store_path)

        # signatures org2 admin
        org2_admin = get_peer_org_user(self.client, 'org2.example.com')
        org2_admin_tx_context = TXContext(org2_admin, Ecies(), {})
        self.client.tx_context = org2_admin_tx_context

        org2_admin_signature = self.client.sign_channel_config(config)
        org2_admin_signature.SerializeToString()

        request = {
            'tx_id': tx_id,
            'nonce': nonce,
            'signatures': signatures,
            'config': config,
            'orderer': orderer,
            'channel_name': channel_name
        }

        queue = Queue(1)

        response = self.client.create_channel(request)

        response.subscribe(on_next=lambda x: queue.put(x),
                           on_error=lambda x: queue.put(x))

        status, _ = queue.get(timeout=5)
        self.assertEqual(status.status, 400)