Fabric-ca is a certificate management tool for Hyperledger Fabric, which is very convenient for development and testing. In this tutorial we’ll explore the use of Fabric-ca and use it to complete user Enrollment /Register and Enrollment /Enrollment.
Hyperledger Fabric is a licensed blockchain platform that requires identification and permission before accessing a Fabric network. Identity in a Fabric network is implemented using digital certificates, so a CA is required to handle certificate management.
Although Hyperledger Fabric allows third-party CA software to manage user certificates, it also comes with a Fabric CA tool for convenience that can act as a CA in a Fabric network. Because the Fabric native application instances use the Fabric CA, we will explore the Fabric CA in this tutorial, especially its use in user registries.
In this article, we use the Fabcar application deployed on the First network. This example application contains both the chain code and the client application, where enroladmin.js and registerUser.js implement the Fabric CA-based registration.
We adjusted the code to make the process clearer. We will also look at the Fabric CA database to better understand how the Fabric CA operates during registration and registration.
Recommended tutorials:
- Hyperledger Fabric Java chain code and application development in detail
- Hyperledger Fabric Node.js chain code and application development details
1, install,
We need a Fabric node to run the Fabric CA demo, which should contain all Hyperledger Fabric-related software. If you don’t already have a Fabric node, refer to this article to create one.
Once the Fabric node is ready, you can start the Fabcar demo by running the following command:
cd fabric-samples/fabcar
./startFabric.sh
Copy the code
This script starts the First network and the CA for each organization. Let’s focus first on Org1’s Fabric-CA.
We use JavaScript code in the Fabcar app, especially enrolladmin.js and registerUser.js, because both parts of the code are coded with the SDK to access the Fabric CA and Fabric network.
This is how the First network and client applications interact with the Fabric network. Let’s focus again on ca_peerOrg1 and the code to register.
2. Fabric CA registration code
There are two processes involved in accessing the Fabric CA. Enrollment refers to requests and acquisition of digital certificates from a specified CA. Registration is usually done by a registrar, who instructs the CA to issue a digital certificate.
There are several different ways to issue digital certificates to users. The flow of the Fabcar script looks like this:
- The administrator is registered with the Fabric CA, and the administrator receives the signed private key and certificate, which are stored in the Wallet /admin directory
- The administrator registers user1 with the Fabric CA and the CA returns a ciphertext
- The ciphertext returned by the CA is used to register user1 in the Fabric CA. After registration, user1’s signed private key and certificate are obtained. These data are stored in the Wallet /user1 directory and will be used for subsequent chain code interactions (queries, transactions).
Enrolladmin.js performs steps 1, registeruser.js performs steps 2 and 3:
3. Modify the Fabric CA sample code
We don’t modify enrolladmin.js, it simply uses the default administrator information (admin: AdminPW), which is preset in the docker-comement-ca.yaml under the fabric-samples/first-network/ directory. The result is admin’s signed private key and certificate, stored in the Wallet /admin directory.
Regsiteruser.js is split into two files, reguser.js and enrolluser.js, because:
- We can observe differences in Fabric CA user registration and registries.
- We can see that the two steps are actually performed by different roles: the registration step is performed by the registrar (admin), while the registration step is performed by the user himself using the obtained ciphertext. This is important because only the user can know the key, and the administrator should not know the key either.
- We can pull out the hard-coded parts of the code as parameters, which can adapt the code to other Fabric CA application scenarios.
The following is an example of the rewritten code:
4. Fabric CA user registration: reguser.js
Reguser.js takes one argument: registration ID, and returns a ciphertext that will later be used for user registration. Note that execution of reguser.js requires the presence of an admin wallet in the Fabric CA.
node regUser.js <enrollmentID>
Copy the code
Most of the code is copied from the original registeruser.js:
/*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const { FileSystemWallet, Gateway, X509WalletMixin } = require('fabric-network');
const path = require('path');
const ccpPath = path.resolve(__dirname, '.. '.'.. '.'first-network'.'connection-org1.json');
async function main() {
try {
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
const user = process.argv[2];
// Check to see if we've already enrolled the user. const userExists = await wallet.exists(user); if (userExists) { console.log('An identity for the user ' + user + ' already exists in the wallet'); return; } // Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists('admin');
if(! adminExists) { console.log('An identity for the admin user "admin" does not exist in the wallet');
console.log('Run the enrollAdmin.js application before retrying');
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'admin', discovery: { enabled: true, asLocalhost: true}}); // Get the CA client object from the gatewayfor interacting with the CA.
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: user, role: 'client' }, adminIdentity);
console.log('Successfully registered user ' + user + ' and the secret is ' + secret );
} catch (error) {
console.error(`Failed to register user ${user}: ${error}`);
process.exit(1);
}
}
main();
Copy the code
Fabric CA enrollment user: enrolluser.js
Enrolluser.js takes two parameters, the enrollment ID and the ciphertext you got when you registered, and returns the wallet created in the Wallet directory. Note that the admin wallet in the Fabric CA is not required to run. This file should be executed by the user himself.
node enrollUser.js <enrollmentID> <secret>
Copy the code
Most of the code comes from the original enrolladmin.js:
/*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin } = require('fabric-network');
const fs = require('fs');
const path = require('path');
const ccpPath = path.resolve(__dirname, '.. '.'.. '.'first-network'.'connection-org1.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
async function main() {
try {
// Create a new CA client for interacting with the CA.
const caInfo = ccp.certificateAuthorities['ca.org1.example.com'];
const caTLSCACerts = caInfo.tlsCACerts.pem;
const ca = new FabricCAServices(caInfo.url, { trustedRoots: caTLSCACerts, verify: false }, caInfo.caName);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
const user = process.argv[2];
const secret = process.argv[3];
// Check to see if we've already enrolled the admin user. const userExists = await wallet.exists(user); if (userExists) { console.log('An identity for this user already exists in the wallet'); return; } // Enroll the admin user, and import the new identity into the wallet. const enrollment = await ca.enroll({ enrollmentID: user, enrollmentSecret: secret }); const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes()); await wallet.import(user, identity); console.log(`Successfully enrolled user ${user} and imported it into the wallet`); } catch (error) { console.error(`Failed to enroll admin user "admin": ${error}`); process.exit(1); } } main();Copy the code
6, presentations,
Now let’s look at how to use these three scripts to register the user1 user in the Fabric CA for the Fabcar application.
First, run fabcar/startFabric.sh
Ensure that the Fabric CA’s wallet directory is empty before running.
cd fabric-samples/fabcar
./startFabric.shcd javascript
rm -rf wallet
Copy the code
The results are as follows:
Step 2, install the dependency module.
npm install
Copy the code
Step 3, install SQlite3 for the Fabric CA of org1
Since we are looking at the Fabric CA database, install SQlite3.
Open another terminal:
docker exec -it ca_peerOrg1 bash
Copy the code
Install sqlite3 for ca_peerOrg1:
apt-get update
apt-get install sqlite3
Copy the code
The Fabric CA database path is /etc/hyperledger/fabric-ca-server/fabric-ca-server.db. The Fabric CA database path is /etc/hyperledger/fabric-ca-server/fabric-ca-server.db.
cd /etc/hyperledger/fabric-ca-server
sqlite3 fabric-ca-server.db
Copy the code
Now you have entered the sqlite3 command line:
sqlite> .tables
Copy the code
The results are as follows:
We are interested in the Users and certificates tables of the Fabric CA, which can be viewed using SQL statements:
sqlite> select * from users;
sqlite> select * from certificates;
Copy the code
The results are as follows:
We see that user admin is already in the database. This is generated when the Fabric CA is started, and this admin has almost all roles, but no certificates have been generated yet.
Now we can start the first registration: registering admin.
Step 4, register admin in the Fabric CA
Wallet /admin: register with admin to get its signature private key and certificate.
node enrollAdmin.js
Copy the code
Results:
Now look at the Users table again:
You can see that one of the admin fields changes from 0 to 1. This is its status field, indicating that a certificate has been issued.
If we quickly compare this to a file in the Fabric CA wallet directory wallet/admin, we see admin’s real certificate:
Now register user1 in the Fabric CA:
node regUser.js user1
Copy the code
The results are as follows:
We now receive the ciphertext MDfRiAUccsna, which is required for user registration. In the Fabric CA wallet directory, we haven’t seen user1’s wallet yet.
By looking at the Fabric CA database, you can clearly see what is happening. We see that users1 has been added to the Users table, but its certificate has not yet been issued. The attributes of user1 are consistent with the information in reguser.js. In addition, user1 has a status of 0, indicating that its certificate has not been issued.
Step 5, register user1 with the Fabric CA to obtain the private key and certificate
Run enrolluser.js to enroll user1:
node enrollUser.js user1 MDfRiAUccsna
Copy the code
The results are as follows:
We see that user1 now appears in Fabri CA’s wallet. We also see that the certificate for user1 has been created in the Fabric CA database:
If the status changes from 0 to 1, the certificate is issued:
Step 6, run the query script with user1 to check for permissions
node query.js
Copy the code
The results are as follows:
Faric CA tutorial – Hui Zhi net