当前位置: 首页 > 知识库问答 >
问题:

Hyperledger结构中查询值的证书验证错误

白烨煜
2023-03-14

我已经根据Hyperledger fabric文档中的“Build your First Network”示例启动了Docker容器和通道。我试图使用Fabric Java SDK从分类帐中查询一个值。我使用的Fabric samples发布版本是fabric-samples-release-1.0。

在通道初始化期间,我得到了一个证书验证失败的异常,这里是我的Java代码

public class javaSDKSample {

private static final Logger log = Logger.getLogger(HFJavaSDKBasicExample.class);


public static void main(String[] args) throws Exception {
    // create fabric-ca client
    HFCAClient caClient = getHfCaClient("http://{remotemachineURL}:7054", null);

    // enroll or load admin
    AppUser admin = getAdmin(caClient);
    log.info(admin);

    // register and enroll new user
   // AppUser appUser = getUser(caClient, admin, "hfuser7");
   // log.info(appUser);

    // get HFC client instance
    HFClient client = getHfClient();
    // set user context
    client.setUserContext(admin);

    // get HFC channel using the client
     Channel channel = getChannel(client);
    log.info("Channel: " + channel.getName());

   //createCar(client, channel, "CAR18", "MAKE7", "MODEL7", "BLACK", "JOHN", true); 


  // queryBlockChain(client);
}


/**
 * Invoke blockchain query
 *
 * @param client The HF Client
 * @throws ProposalException
 * @throws InvalidArgumentException
 */
static void queryBlockChain(HFClient client) throws ProposalException, InvalidArgumentException {
    // get channel instance from client
    Channel channel = client.getChannel("mychannel");
    // create chaincode request
    QueryByChaincodeRequest qpr = client.newQueryProposalRequest();
    // build cc id providing the chaincode name. Version is omitted here.
    ChaincodeID fabcarCCId = ChaincodeID.newBuilder().setName("mycc").build();
    qpr.setChaincodeID(fabcarCCId);
    // CC function to be called
    qpr.setFcn("query");
    qpr.setArgs(new String[]{"a"});
    Collection<ProposalResponse> res = channel.queryByChaincode(qpr);
    // display response
    for (ProposalResponse pres : res) {
        String stringResponse = new String(pres.getChaincodeActionResponsePayload());
        log.info(stringResponse);
    }
}


static void createCar(HFClient client,Channel channel, String key, String make,String model,String color,String owner, Boolean doCommit)
        throws Exception {
    TransactionProposalRequest req = client.newTransactionProposalRequest();
    ChaincodeID cid = ChaincodeID.newBuilder().setName("fabcar").build();
    req.setChaincodeID(cid);
    req.setFcn("createCar");
    req.setArgs(new String[] { key, make,model,color,owner });
    System.out.println("Executing for " + key);
    Collection<ProposalResponse> resps = channel.sendTransactionProposal(req);
    if (doCommit) {
        channel.sendTransaction(resps);
    }
} 




/**
 * Initialize and get HF channel
 *
 * @param client The HFC client
 * @return Initialized channel
 * @throws InvalidArgumentException
 * @throws TransactionException
 */
static Channel getChannel(HFClient client) throws InvalidArgumentException, TransactionException {
    // initialize channel
    // peer name and endpoint in fabcar network

    Properties peerProperties = new Properties();
    peerProperties.setProperty("pemFile", "D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt"); 
    peerProperties.setProperty("trustServerCertificate", "true"); //testing environment only NOT FOR PRODUCTION!    
    peerProperties.setProperty("hostnameOverride", "peer0.org1.example.com");
    peerProperties.setProperty("sslProvider", "openSSL");
    peerProperties.setProperty("negotiationType", "TLS");
    peerProperties.put("grpc.NettyChannelBuilderOption.maxInboundMessageSize", 9000000);
    Peer peer = client.newPeer("peer0.org1.example.com", "grpcs://{remotemachineURL}:7051");
    // eventhub name and endpoint in fabcar network
    final Properties eventHubProperties = new Properties();
    eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] {5L, TimeUnit.MINUTES});
    eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] {8L, TimeUnit.SECONDS});
    EventHub eventHub = client.newEventHub("eventhub01", "grpcs://{remotemachineURL}:7053",eventHubProperties);
    // orderer name and endpoint in fabcar network
Properties ordererProperties = new Properties();
 ordererProperties.setProperty("pemFile", "D:/FabricCert/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt");
    ordererProperties.setProperty("trustServerCertificate", "true"); //testing environment only NOT FOR PRODUCTION!
    ordererProperties.setProperty("hostnameOverride", "orderer.example.com");
    ordererProperties.setProperty("sslProvider", "openSSL");
    ordererProperties.setProperty("negotiationType", "TLS");
    ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] {5L, TimeUnit.MINUTES});
    ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] {8L, TimeUnit.SECONDS});
    Orderer orderer = client.newOrderer("orderer.example.com", "grpcs://{remotemachineURL}:7050");
    // channel name in fabcar network
    Channel channel = client.newChannel("mychannel");
    channel.addPeer(peer);
    channel.addEventHub(eventHub);
    channel.addOrderer(orderer);
    channel.initialize();
    return channel;
}

/**
 * Create new HLF client
 *
 * @return new HLF client instance. Never null.
 * @throws CryptoException
 * @throws InvalidArgumentException
 */
static HFClient getHfClient() throws Exception {
    // initialize default cryptosuite
    CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
    // setup the client
    HFClient client = HFClient.createNewInstance();
    client.setCryptoSuite(cryptoSuite);
    return client;
}


/**
 * Register and enroll user with userId.
 * If AppUser object with the name already exist on fs it will be loaded and
 * registration and enrollment will be skipped.
 *
 * @param caClient  The fabric-ca client.
 * @param registrar The registrar to be used.
 * @param userId    The user id.
 * @return AppUser instance with userId, affiliation,mspId and enrollment set.
 * @throws Exception
 */
static AppUser getUser(HFCAClient caClient, AppUser registrar, String userId) throws Exception {
    AppUser appUser = tryDeserialize(userId);
    System.out.println("appUser"+appUser);
    if (appUser == null) {
        RegistrationRequest rr = new RegistrationRequest(userId, "org1");
        String enrollmentSecret = caClient.register(rr, registrar);            
        Enrollment enrollment = getEnrollment();
        enrollment =  caClient.enroll(userId, enrollmentSecret);
        byte[] certFile = Base64.encodeBase64(enrollment.getCert().getBytes()); 
        byte[] keyFile = Base64.encodeBase64(enrollment.getKey().toString().getBytes());   

        BufferedWriter bufferedWriter = null;
        File myFile = new File("D:/keyfile.key");
        // check if file exist, otherwise create the file before writing
        if (!myFile.exists()) {
            myFile.createNewFile();
        }
        Writer writer = new FileWriter(myFile);
        bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.write(enrollment.getKey().toString());
        bufferedWriter.close();
        appUser = new AppUser(userId, "org1", "Org1MSP", enrollment);
        serialize(appUser);
    }
    return appUser;
}


public static Enrollment getEnrollment() {
    return new Enrollment() {
        public PrivateKey getKey() {
            PrivateKey privateKey = null;
            try {
                File privateKeyFile = findFileSk("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore");
                privateKey = getPrivateKeyFromBytes(IOUtils.toByteArray(new FileInputStream(privateKeyFile)));
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return privateKey;
        }

        public String getCert() {

            String certificate = null;
            try {
                File certificateFile = new File("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem");
                certificate = new String(IOUtils.toByteArray(new FileInputStream(certificateFile)), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return certificate;
        }
    };
}

static PrivateKey getPrivateKeyFromBytes(byte[] data) throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    final Reader pemReader = new StringReader(new String(data));

    final PrivateKeyInfo pemPair;
    try (PEMParser pemParser = new PEMParser(pemReader)) {
        pemPair = (PrivateKeyInfo) pemParser.readObject();
    }

    PrivateKey privateKey = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);

    return privateKey;
}



/**
 * Enroll admin into fabric-ca using {@code admin/adminpw} credentials.
 * If AppUser object already exist serialized on fs it will be loaded and
 * new enrollment will not be executed.
 *
 * @param caClient The fabric-ca client
 * @return AppUser instance with userid, affiliation, mspId and enrollment set
 * @throws Exception
 */
static AppUser getAdmin(HFCAClient caClient) throws Exception {
    AppUser admin = tryDeserialize("admin");
    if (admin == null) {
        Enrollment adminEnrollment = caClient.enroll("admin", "adminpw");
        admin = new AppUser("admin", "org1", "Org1MSP", adminEnrollment);
        serialize(admin);
    }
    return admin;
}

/**
 * Get new fabric-ca client
 *
 * @param caUrl              The fabric-ca-server endpoint url
 * @param caClientProperties The fabri-ca client properties. Can be null.
 * @return new client instance. never null.
 * @throws Exception
 */
static HFCAClient getHfCaClient(String caUrl, Properties caClientProperties) throws Exception {
    CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
    HFCAClient caClient = HFCAClient.createNewInstance(caUrl, caClientProperties);
    caClient.setCryptoSuite(cryptoSuite);
    return caClient;
}


// user serialization and deserialization utility functions
// files are stored in the base directory

/**
 * Serialize AppUser object to file
 *
 * @param appUser The object to be serialized
 * @throws IOException
 */
static void serialize(AppUser appUser) throws IOException {
    try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(
            Paths.get(appUser.getName() + ".jso")))) {
        oos.writeObject(appUser);
    }
}

/**
 * Deserialize AppUser object from file
 *
 * @param name The name of the user. Used to build file name ${name}.jso
 * @return
 * @throws Exception
 */
static AppUser tryDeserialize(String name) throws Exception {
    if (Files.exists(Paths.get(name + ".jso"))) {
        return deserialize(name);
    }
    return null;
}

static AppUser deserialize(String name) throws Exception {
    try (ObjectInputStream decoder = new ObjectInputStream(
            Files.newInputStream(Paths.get(name + ".jso")))) {
        return (AppUser) decoder.readObject();
    }
}
static File findFileSk(String directorys) {

    File directory = new File(directorys);

    File[] matches = directory.listFiles((dir, name) -> name.endsWith("_sk"));

    if (null == matches) {
        throw new RuntimeException(format("Matches returned null does %s directory exist?", directory.getAbsoluteFile().getName()));
    }

    if (matches.length != 1) {
        throw new RuntimeException(format("Expected in %s only 1 sk file but found %d", directory.getAbsoluteFile().getName(), matches.length));
    }

    return matches[0];
}}

共有1个答案

萧光华
2023-03-14

代码起作用了,显然注册有一些问题。我用了一个坏证书。更改了注册证书,并解决了问题。谢谢

 类似资料:
  • 当我想要在cPanel上安装证书时,我会看到以下错误: 错误证书验证失败! 已执行/usr/bin/openssl verify-capath/var/cpanel/ssl/installed/cabundles: stdin:CN=example.com 0深度查找时错误20:无法获取本地颁发者证书

  • 假设我编写了两个Java应用程序:和,它们在两个独立的服务器上部署和运行(部署到和部署到

  • 我使用的是Hyperledger Fabric版本1.2。我创建了一个有1个订购者和10个对等节点的通道,所有这些节点都属于同一个组织。我想用背书策略实例化链码,这样ORG1的所有对等体都是背书对等体,而不仅仅是1。相同的有效表达式是什么? Fabric文档包含包括来自不同组织的同行的示例。

  • 误差 PHP警告:stream_socket_client():SSL操作失败,代码为1。OpenSSL错误消息:错误:14090086:SSL例程:SSL3_GET_Server_Certifice:证书验证失败

  • 问题内容: 我正在尝试使用url从jira服务器下载文件,但出现错误。如何在代码中包括证书以验证 错误: 我的Nodejs代码: 问题答案: 尝试添加适当的根证书 这总是比盲目地接受未经授权的端点要安全得多的选择,后者只能被用作最后的手段。 这可以像添加一样简单 到您的应用程序。 该SSL根CA NPM包(这里使用的)是关于这个问题的一个非常有用的包。

  • 我试图使用URL从jira服务器下载一个文件,但我遇到了一个错误。如何在代码中包含证书以进行验证? 错误: 我的Nodejs代码: